簡體   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