2016-07-01 92 views
2

为什么我得到不同的出把两只宽度和高度变量在下面的程序输出不一样传递的参数

#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 
+0

如果你打开你的编译器警告,它应该告诉你发生了什么事情。 – Galik

回答

11

的问题在于int widthint height在函数参数列表中隐藏了widthheight类成员变量,因为它们具有相同的名称。你的函数做的是将传入的值赋给它们自己,然后存在。这意味着该类中的widthheight未被初始化,并且它们保留一些未知值。你需要,如果你想的名字是一样的做的是使用this指针diferentiate像

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->

而不是有一个设置功能,你可以使用一个构造函数,并在创建它时初始化该对象。像

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

构造函数这里为编译器知道哪一个是成员,其中一个是参数,我们可以使用相同的名称

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

相关问题