将私有结构设置为返回值

时间:2016-11-26 23:56:09

标签: c++ struct

对于类赋值,我们需要在类中有一个私有结构,但是我们需要具有与返回值相同的结构(而不​​是指向它的指针)。这些方面的东西:

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

public:
    struct Employee find(int key);

这可能只使用STL吗?

1 个答案:

答案 0 :(得分:0)

它可以完成,但没有多大意义,因为界面应该是公开的。

例如

#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;
}

程序输出

First