gpt4 book ai didi

c++ - 程序的输出与传递的参数不同

转载 作者:太空狗 更新时间:2023-10-29 23:35:24 26 4
gpt4 key购买 nike

为什么我在下面的程序中得到不同的宽度和高度变量输出

#include <iostream>

using namespace std;

class my_space {
public :
void set_data(int width,int height) // taking the same name of the variable as the class member functions
{
width = width;
height = height;
}
int get_width()
{
return width;
}
int get_height()
{
return height;
}
private :
int width;
int height;
};


int main() {
my_space m;
m.set_data(4,5); // setting the name of private members of the class
cout<<m.get_width()<<endl;
cout<<m.get_height()<<endl;
return 0;
}

低于程序的输出

sh-4.3$ main                                                                                                                                                        
1544825248
32765

最佳答案

这里的问题是函数参数列表中的int widthint height隐藏了widthheight类成员变量,因为它们具有相同的名称。您的函数所做的是将传入的值分配给它们自己然后存在。这意味着类中的 widthheight 未初始化,它们包含一些未知值。如果您希望名称相同,您需要做的是使用 this 指针来区分名称,例如

void set_data(int width,int height) // taking the same name of the variable as the class member functions
{
this->width = width;
this->height = height;
}

现在编译器知道哪个是哪个了。您也可以将函数参数命名为其他名称,这样就不需要使用 this->

此外,您还可以使用构造函数并在创建对象时初始化对象,而不是使用 set 函数。像这样的构造函数

my_space(int width = 0, int height = 0) : width(width), height(height) {}

这里我们可以使用相同的名称,因为编译器知道哪个是成员,哪个是参数

将始终确保该类至少默认构造为已知状态,或者您可以提供自己的值以使其成为非默认状态。

关于c++ - 程序的输出与传递的参数不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38145314/

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