[英]What is the order of control flow while compiling the code for a class in C++?
我正在編譯一個 class,完整的程序如下:
#include<iostream>
using namespace std;
class Test{
public:
Test()
{
cout<<"Test variable created...\n";
// accessing width variable in constructor
cout<<"Width is "<<width<<".\n";
}
void setHeight(int h)
{
height = h;
}
void printHeight()
{
cout<<"Height is "<<height<<" meters.\n";
}
int width = 6;
protected:
int height;
};
int main()
{
Test t = Test();
t.setHeight(3);
t.printHeight();
return 0;
}
代碼工作得很好,但是構造函數如何能夠訪問直到public
塊結束才聲明的變量width
。 此外,成員函數如何能夠訪問稍后在公共塊中聲明的變量? C++ 不是順序的(按照它們編寫的順序執行語句)?
將 class 中的內聯定義視為聲明 function 的語法糖,然后在 class 之外進行定義。 手動這樣做會將代碼轉換為
class Test{
public:
Test();
void setHeight(int h);
void printHeight();
int width = 6;
protected:
int height;
};
Test::Test()
{
cout<<"Test variable created...\n";
// accessing width variable in constructor
cout<<"Width is "<<width<<".\n";
}
void Test::setHeight(int h)
{
height = h;
}
void Test::printHeight()
{
cout<<"Height is "<<height<<" meters.\n";
}
您可以從這個轉換中看到 class 成員現在位於 function 定義“之前”,因此他們沒有理由不知道該變量。
The technical term for this is call the complete-class context and the jist of it is that when you are in the body of a member function or the class member initialization list, the class is considered complete and can use anything defined in the class,無論在 class 中的哪個位置聲明它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.