简体   繁体   English

C ++定义类成员结构并在成员函数中返回它

[英]C++ define class member struct and return it in a member function

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不是类型名称。

It makes sense to make the nested structure type public, since the user code should be able to use it. 将嵌套结构类型设置为public是有意义的,因为用户代码应该能够使用它。 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. 在类范围之外使用scope resolution ::来引用嵌套类型。

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

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 before the function that uses it. 另请注意,必须在使用它的函数之前定义它。

You need to change the order of the members of UserInformation and put struct UserInfo above the declaration of getInfo . 您需要更改UserInformation成员的顺序,并将struct UserInfo 置于 getInfo声明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. 编译器抱怨它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结构。

Just do UserInformation::userInfo UserInformation::getInfo(int userId) . 只需执行UserInformation::userInfo UserInformation::getInfo(int userId)

Also, you should declare userInfo public. 此外,您应该声明userInfo public。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM