将私有结构设置为返回值 [英] Setting a private struct as a return value
本文介绍了将私有结构设置为返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于类赋值,我们需要在类中有一个私有结构,但我们需要有相同的结构作为返回值(而不是指向它的指针).一些类似的东西:
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);
这是否可以仅使用 STL?
Is this possible using exclusively the STL?
推荐答案
可以做到,但意义不大,因为接口应该是公开的.
It can be done but does not make great sense because the interface should be public.
例如
#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
这篇关于将私有结构设置为返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文