C++定义类成员结构体并在成员函数中返回
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5523109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ define class member struct and return it in a member function
提问by yolo
My goal is a class like:
我的目标是这样的课程:
class UserInformation
{
public:
userInfo getInfo(int userId);
private:
struct userInfo
{
int repu, quesCount, ansCount;
};
userInfo infoStruct;
int date;
};
userInfo UserInformation::getInfo(int userId)
{
infoStruct.repu = 1000;
return infoStruct;
}
but the compiler gives error that in defintion of the public function getInfo(int)
the return type userInfo
is not a type name.
但是编译器给出了错误,即在公共函数getInfo(int)
的定义中,返回类型userInfo
不是类型名称。
采纳答案by Jon
You need to change the order of the members of UserInformation
and put struct UserInfo
abovethe declaration of getInfo
. The compiler complains that it can't work out the signature for getInfo
because it hasn't seen the definition of its return type yet.
您需要更改的成员的顺序UserInformation
,把struct UserInfo
上面的声明getInfo
。编译器抱怨它无法计算出签名,getInfo
因为它还没有看到其返回类型的定义。
Also, if you are returning a struct from the function the type of the struct must be visible to the callers. So you need to make the struct public
as well.
此外,如果您从函数返回一个结构体,则该结构体的类型必须对调用者可见。所以你也需要制作结构public
。
回答by pic11
It makes sense to make the nested structure type public, since the user code should be able to use it. Also, place the declaration of the structure before the point of its first use. Outside the class scope use scope resolution ::to refer to nested types.
将嵌套结构类型公开是有意义的,因为用户代码应该能够使用它。此外,将结构的声明放在第一次使用的位置之前。在类范围之外,使用范围解析::来引用嵌套类型。
class UserInformation
{
public:
struct UserInfo
{
int repu, quesCount, ansCount;
};
public:
UserInfo getInfo(int userId);
private:
UserInfo infoStruct;
int date;
};
UserInformation::UserInfo UserInformation::getInfo(int userId)
{
infoStruct.repu = 1000;
return infoStruct;
}
回答by Oliver Charlesworth
If the member function is public, then the return type must be publicly visible! Therefore, move the inner struct definition into the public
section.
如果成员函数是公开的,那么返回类型必须是公开可见的!因此,将内部结构定义移动到public
节中。
Note also that it must be defined beforethe function that uses it.
还要注意它必须在使用它的函数之前定义。
回答by Alexander Gessler
Just do UserInformation::userInfo UserInformation::getInfo(int userId)
.
就做UserInformation::userInfo UserInformation::getInfo(int userId)
。
Also, you should declare userInfo
public.
另外,你应该声明userInfo
public。