简体   繁体   中英

Scope resolution operator for returning a nested class type

I know that the scope resolution operator :: is used to identify and disambiguate identifiers used in different scopes.

In the example provided here C++ define class member struct and return it in a member function

class UserInformation
{
public:
    userInfo getInfo(int userId);
private:
    struct userInfo
    {
        int repu, quesCount, ansCount;
    };
    userInfo infoStruct;
    int date;
};

You can create a member function that returns a type of the nested class userInfo .

UserInformation::UserInfo UserInformation::getInfo(int userId)   <-----
{
    Userinfo x;            <-----
    infoStruct.repu = 1000;
    return infoStruct;
}
  1. Why does the scope have to be stated twice in the function definition? UserInformation::UserInfo UserInformation::getInfo(int userId) It's an error if it's only stated once, but from my understanding, I thought that stating it once at the beginning, before the return value would put us in the correct scope already?
  2. In the function above, I added Userinfo x; to show that the nested class type can be declared and used without the scope resolution operator. Why is that allowed?
  1. The class scope is needed for the function return type because name lookup won't yet know of it.

You can get around that requirement if you wish with C++11 trailing function return type.

auto UserInformation::getInfo(int userId) -> UserInfo
{ ... }
  1. The class scope is not needed inside the member function body because there the class scope is then obviously known.
  1. Why does the scope have to be stated twice in the function definition? UserInformation::UserInfo UserInformation::getInfo(int userId)

For both, the return type and the function identifier, the outer scope (outside of class UserInformation ) is applied.

  1. In the function above, I added Userinfo x; to show that the nested class type can be declared and used without the scope resolution operator. Why is that allowed?

UserInformation::getInfo() is a member function of class UserInformation . Inside, the function body, an additional (invisible) argument is assumed which is accessible with this (the pointer to instance for which the function was called for).

The scope of the member function involves the scope of the class it belongs to. This covers the embedded types as well as member variables and functions which are implicitly prefixed with ( this-> ) if not eclipsed (eg by a local variable with same identifier).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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