为什么我在下面的程序中得到宽度和高度变量的不同
#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;
}
Run Code Online (Sandbox Code Playgroud)
低于该程序的输出
sh-4.3$ main
1544825248
32765
Run Code Online (Sandbox Code Playgroud)
Nat*_*ica 11
这里的问题是,int width与int height在函数参数列表隐藏width和height类的成员变量,因为具有相同的名称.你的函数做的是将传入的值赋给自己然后存在.这意味着在课堂上width和height课堂上都没有初始化,并且它们具有一些未知的价值.如果您希望名称相同,则需要执行的操作是使用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;
}
Run Code Online (Sandbox Code Playgroud)
现在编译器知道哪个是哪个.您也可以将函数参数命名为其他东西,然后您就不需要使用了this->.
此外,您可以使用构造函数并在创建对象时初始化对象,而不是使用set函数.一个像.的构造函数
my_space(int width = 0, int height = 0) : width(width), height(height) {}
Run Code Online (Sandbox Code Playgroud)
在这里,我们可以使用相同的名称,因为编译器知道哪一个是成员,哪一个是参数
将始终确保该类至少默认构造为已知状态,或者您可以提供自己的值以使其成为非默认状态.
| 归档时间: |
|
| 查看次数: |
35 次 |
| 最近记录: |