C++ define class member struct and return it in a

2020-02-25 23:20发布

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.

4条回答
孤傲高冷的网名
2楼-- · 2020-02-25 23:37

You need to change the order of the members of UserInformation and put struct UserInfo above the 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.

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.

查看更多
手持菜刀,她持情操
3楼-- · 2020-02-25 23:37

Just do UserInformation::userInfo UserInformation::getInfo(int userId).

Also, you should declare userInfo public.

查看更多
▲ chillily
4楼-- · 2020-02-25 23:45

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;
}
查看更多
\"骚年 ilove
5楼-- · 2020-02-25 23:47

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.

查看更多
登录 后发表回答