Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 312
yolo Avatar asked Apr 02 '11 12:04

yolo


People also ask

Can structs have member functions in C?

1. Member functions inside the structure: Structures in C cannot have member functions inside a structure but Structures in C++ can have member functions along with data members.

Can I declare a struct inside a class?

Yes you can. In c++, class and struct are kind of similar. We can define not only structure inside a class, but also a class inside one. It is called inner class.

Can a function be a member of a struct answer?

Yes, there is a clear answer: C++ struct can have member functions.

Is class member and member function same?

Member functions are operators and functions that are declared as members of a class. Member functions do not include operators and functions declared with the friend specifier. These are called friends of a class. You can declare a member function as static ; this is called a static member function.


1 Answers

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.

like image 55
Oliver Charlesworth Avatar answered Sep 25 '22 13:09

Oliver Charlesworth