2013-12-08 105 views
0
#include<iostream> 
using namespace std; 

class a 
{ 
private: 
    int x; 
    int y; 
public: 
    int getx() 
    { 
     return x; 
    } 
    int gety() 
    { 
     return y; 
    } 
    a() 
    { 
     x = 100; 
     y = 100; 
    } 
    void xmin() 
    { 
     x--; 
    } 
    void ab(a x) 
    { 
     x.xmin(); x.xmin(); x.xmin(); x.xmin(); 
    } 
}; 

void main() 
{ 
    a xx; 
    a yy; 
    cout << "xx" << endl; 
    cout << "x : " << xx.getx() << "y : " << xx.gety()<<endl; 
    cout << "yy" << endl; 
    cout << "x : " << yy.getx() << "y : " << yy.gety()<<endl; 
    xx.ab(yy); 
    cout << "xx" << endl; 
    cout << "x : " << xx.getx() << "y : " << xx.gety() << endl; 
    cout << "yy" << endl; 
    cout << "x : " << yy.getx() << "y : " << yy.gety() << endl; 
} 

为什么函数x.xmin()void ab(a x)中无法正确执行? (中x的价值并没有改变作为xmin()功能由1不能调用类函数(参数类)

减少x值这是我的代码的简单版本,这样会更容易理解:)

+0

您传递的值作为PARAM不是对象它的自我,你必须通过参考'无效AB(A&X)' – rednaks

+1

应该是'int main' –

回答

2
void ab(a x) 

这是以价值为依据的。该函数修改参数的本地副本,因此调用者不会看到任何更改。如果你想要的功能修改调用者的物体,然后通过引用传递:

void ab(a & x) 
     ^