Setting a private struct as a return value

2019-07-26 10:24发布

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?

标签: c++ struct
1条回答
Explosion°爆炸
2楼-- · 2019-07-26 11:10

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
查看更多
登录 后发表回答