我正在编译一个类,下面是完整的程序:
#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;
}
代码运行得非常好,但是构造函数如何能够访问变量
width
在public
块结束之前没有被声明。此外,成员函数如何能够访问稍后在公共块中声明的变量?C++不是按照顺序执行语句的吗?
int height{};
,这样用户在没有调用setHeight()
的情况下尝试printHeight()
就不会引起未定义的行为。 - underscore_dint width = 6;
)。这意味着在第一个非静态方法被调用之前,必须知道类的结构。 - Thomas Sablik