C++定义类成员结构并在成员函数中返回它
我的目标是这样的类:
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;
}
但编译器给出错误,在公共函数 getInfo(int)
的定义中,返回类型 userInfo
不是类型名称。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将嵌套结构类型公开是有意义的,因为用户代码应该能够使用它。另外,将结构声明放在第一次使用点之前。在类作用域之外,使用作用域解析 :: 来引用嵌套类型。
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.
如果成员函数是公共的,那么返回类型必须是公共可见的!因此,将内部结构定义移至
public
部分。另请注意,它必须在使用它的函数之前定义。
If the member function is public, then the return type must be publicly visible! Therefore, move the inner struct definition into the
public
section.Note also that it must be defined before the function that uses it.
只需执行
UserInformation::userInfo UserInformation::getInfo(int userId)
即可。另外,您应该将
userInfo
声明为公共。Just do
UserInformation::userInfo UserInformation::getInfo(int userId)
.Also, you should declare
userInfo
public.您需要更改
UserInformation
成员的顺序,并将struct UserInfo
放在getInfo
声明的上方。编译器抱怨它无法计算出getInfo
的签名,因为它还没有看到其返回类型的定义。此外,如果您从函数返回一个结构体,则该结构体的类型必须对调用者可见。因此,您还需要将结构设为 public 。
You need to change the order of the members of
UserInformation
and putstruct UserInfo
above the declaration ofgetInfo
. The compiler complains that it can't work out the signature forgetInfo
because it hasn't seen the definition of its return type yet.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.