C++ 在C+中编译类代码时,控制流的顺序是什么+;?
我正在编译一个类,完整的程序如下所示:C++ 在C+中编译类代码时,控制流的顺序是什么+;?,c++,oop,control-flow,access-specifier,C++,Oop,Control Flow,Access Specifier,我正在编译一个类,完整的程序如下所示: #include<iostream> using namespace std; class Test{ public: Test() { cout<<"Test variable created...\n"; // accessing width variable in constructor cou
#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;
}
#包括
使用名称空间std;
课堂测试{
公众:
测试()
{
可以将类中的内联定义看作是声明函数的语法糖,然后在类外定义
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";
}
类测试{
公众:
Test();
空隙高度(inth);
无效打印高度();
整数宽度=6;
受保护的:
内部高度;
};
Test::Test()
{
Cut声明不是语句。在编译代码之前,收集并存储类的声明。此外,语句不必顺序执行。如果程序的可观察行为在“IF”规则下是相同的,那么C++不是按顺序(按它们的顺序执行语句)吗?不,不是。语句可以按不同的顺序执行,例如,成员初始值设定项列表。这些语句是按照类中列出成员的顺序执行的,而不是按照实际语句的顺序执行的。声明为int height{};
,这样用户就不能通过尝试printHeight()来调用未定义的行为
没有setHeight()
。初始化成员变量(int width=6;
)在调用构造函数之前。这意味着在调用第一个非静态方法之前必须知道类的结构。你可以看到在实际构造函数开始工作之前发生了什么。有更好的文档,但我找不到。在构造函数的初始值设定项列表中也是这样吗?@ViNcRelfMun.是的。成员初始化列表被认为是函数的一部分,谢谢“NaNauliviver,我猜这将是你的答案中的一个有价值的精确性。”VincentFourmond补充说。