gpt4 book ai didi

c++ - 在 C++ 中编译类的代码时,控制流的顺序是什么?

转载 作者:行者123 更新时间:2023-12-04 01:07:36 32 4
gpt4 key购买 nike

我正在编写一个类,完整的程序如下:

#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 block 结束才声明的变量 width 。另外,成员函数如何访问稍后在公共(public) block 中声明的变量? C++ 不是顺序的(按照编写的顺序执行语句)吗?

最佳答案

将类中的内联定义视为声明函数的语法糖,然后在类外部进行定义。手动执行此操作会将代码转换为

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";
}

并且您可以从这个转换中看出,类成员现在位于函数定义“之前”,因此他们没有理由不知道变量。

这个的技术术语是调用 complete-class context它的要点是,当您位于成员函数的主体或类成员初始化列表中时,该类被认为是完整的,并且可以使用类中定义的任何内容,无论它在类中的何处声明。

关于c++ - 在 C++ 中编译类的代码时,控制流的顺序是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65940862/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com