C ++ defines the structure of a class element and returns 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 an error that when defining the public function getInfo(int) the return type of userInfo not a type name.

+7
source share
4 answers

You need to reorder the members of the UserInformation and place the struct UserInfo above the getInfo . The compiler complains that it cannot work out a signature for getInfo , because it has not yet seen a definition of its return type.

In addition, if you are returning a structure from a function, the type of structure must be visible to callers. Therefore, you also need to create a public structure.

+4
source

It makes sense to make the type of nested structure publicly available, since user code should be able to use it. Also, post the structure declaration before it is first used. Outside the scope of the class, use the scope :: resolution to denote 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; } 
+12
source

If the member function is public, then the return type must be public! Therefore, move the definition of the internal structure to the public section.

Note that it must be defined before the function that uses it.

+4
source

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

In addition, you must declare userInfo public.

+4
source

All Articles