繁体   English   中英

Scope 解析运算符,用于返回嵌套的 class 类型

[英]Scope resolution operator for returning a nested class type

我知道 scope 解析运算符::用于识别和消除不同范围内使用的标识符。

在此处提供的示例中 C++ 定义 class 成员结构并将其返回到成员 function

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

您可以创建返回嵌套类型 class userInfo的成员 function 。

UserInformation::UserInfo UserInformation::getInfo(int userId)   <-----
{
    Userinfo x;            <-----
    infoStruct.repu = 1000;
    return infoStruct;
}
  1. 为什么 scope 必须在 function 定义中声明两次? UserInformation::UserInfo UserInformation::getInfo(int userId)如果只声明一次是错误的,但据我了解,我认为在开始时声明一次,在返回值之前将我们置于正确的 scope 已经?
  2. 在上面的function中,我添加了Userinfo x; 表明嵌套 class 类型可以在没有 scope 解析运算符的情况下声明和使用。 为什么允许这样做?
  1. function 返回类型需要 class scope 因为名称查找还不知道它。

如果您希望使用 C++11 尾随 function 返回类型,则可以绕过该要求。

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. 为什么 scope 必须在 function 定义中声明两次? UserInformation::UserInfo UserInformation::getInfo(int userId)

对于这两者,返回类型和 function 标识符,外部 scope(在class UserInformation之外)被应用。

  1. 在上面的function中,我添加了Userinfo x; 表明嵌套 class 类型可以在没有 scope 解析运算符的情况下声明和使用。 为什么允许这样做?

UserInformation::getInfo()class UserInformation的成员 function 。 在内部,function 主体,假设有一个额外的(不可见的)参数,可以通过this访问(指向调用 function 的实例的指针)。

成员function的scope涉及scope的scope,它属于ZA2F2ED4F8EBC2CBB4C21A29DC40AB6。 这涵盖了嵌入类型以及成员变量和函数,如果没有被遮蔽(例如,通过具有相同标识符的局部变量),则隐式地以 ( this-> ) 为前缀。

暂无
暂无

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

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