程序的输出不同于传递的参数 [英] output of program is not same as passed argument
问题描述
为什么我在下面的程序中得到了不同的宽度和高度变量。
Why I am getting different out put of both the width and height variable in below program
#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 width
和 int height
在函数参数列表中隐藏 width
和 height
类成员变量,因为它们具有相同的名称。你的函数做什么是将传递的值赋值给自己然后存在。这意味着类中的 width
和 height
未初始化,并且它们具有某个未知值。如果你想要的名称是相同的,你需要做的是使用 this
指针来区分像
The problem here is that int width
and int height
in function parameter list hide the width
and height
class member variables since the have the same name. What your function does is assign the passed in values to themselves and then exist. This means the width
and height
in the class are left uninitialized and they hold some unknown value. What you need to do if you want the names to be the same is use the this
pointer to diferentiate the names like
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函数。像
Also instead of having a set function you could use a constructor and initialize the object when you create it. A constructor like
my_space(int width = 0, int height = 0) : width(width), height(height) {}
这里我们可以使用相同的名称,因为编译器知道哪一个是成员,其中一个是参数
将始终确保类至少是默认构造为已知状态,或者您可以提供自己的值以使其成为非默认状态。
Will always make sure the class is at least default constructed to a known state or you can provide your own values to make it a non-default state.
这篇关于程序的输出不同于传递的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!