gpt4 book ai didi

c++ - 在声明之前使用成员变量?

转载 作者:行者123 更新时间:2023-11-30 05:24:27 24 4
gpt4 key购买 nike

<分区>

是否可以在声明之前使用类的成员变量?这是我的代码。

using namespace std;
class Computer

{
public:
Computer()
{
processor_speed = 0;
}
~Computer();
void setspeed (int);
int getspeed (void);

private:
int processor_speed;
};
/*Computer::Computer()
{
processor_speed = 0;
} */
Computer::~Computer()
{
cout<<"this is a destructor"<<endl;
}
void Computer:: setspeed(int p)
{
processor_speed = p;
}
int Computer::getspeed(void)
{
return processor_speed;
}

int main(void)
{
Computer obj;
cout<<"processor speed is "<<obj.getspeed()<<endl;
obj.setspeed(100);
cout<<"processor speed is now "<<obj.getspeed()<<endl;
return 0;
}

如您所见,我能够在声明变量之前使用变量 processor_speed。我在这里看到了一个类似的问题:Do class functions/variables have to be declared before being used?但我无法理解这段代码工作的原因。谢谢

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