Setting a private struct as a return value

2019-07-26 11:10发布

问题:

For a class assignment, we are required to have a private struct in a class, but we need to have the same struct as a return value (not a pointer to it). Something along these lines:

private:
    struct Employee 
    {
        int id;
        string name;    
    };

public:
    struct Employee find(int key);

Is this possible using exclusively the STL?

回答1:

It can be done but does not make great sense because the interface should be public.

For example

#include <iostream>
#include <string>

struct C
{
private:
    struct Employee 
    {
        int id;
        std::string name;    
    };

    Employee e = { 1, "First" };

public:
    Employee find(int key) const
    {
        return key == e.id ? e : Employee {};
    }
};

int main() 
{
    C c;

    auto e = c.find( 1 );

    std::cout << e.name << std::endl;

    return 0;
}

The program output is

First


标签: c++ struct