【发布时间】:2014-05-05 18:47:14
【问题描述】:
我想知道我在这里做错了什么。我正在创建一个类a和一个类b,设置b等于a,设置a的值,并打印b的值。但是b的值没有变化。
这是我的代码:
#include <iostream>
using namespace std;
struct Node
{
int x;
int y;
};
class Ball
{
public:
Ball();
Ball(int r, int x, int y);
int GetR();
void SetR(int);
int GetX();
void SetX(int);
int GetY();
void SetY(int);
private:
int m_r;
int m_x;
int m_y;
};
int main(int argc, char* argv[])
{
Ball a;
Ball b;
b = a;
a.SetR(10);
cout << "a.GetR() : " << a.GetR() << endl;
cout << "b.GetR() : " << b.GetR() << endl;
return 0;
}
Ball::Ball()
{
m_r = 0;
m_x = 0;
m_y = 0;
}
Ball::Ball(int r, int x, int y)
{
m_r = r;
m_x = x;
m_y = y;
}
int Ball::GetR()
{
return m_r;
}
void Ball::SetR(int r)
{
m_r = r;
}
int Ball::GetX()
{
return m_x;
}
void Ball::SetX(int x)
{
m_x = x;
}
int Ball::GetY()
{
return m_y;
}
void Ball::SetY(int y)
{
m_y = y;
}
这是我的终端输出:
a.GetR() : 10
b.GetR() : 0
谁能向我解释 C++ 中类通过引用的工作原理以及为什么会发生这种情况?
提前谢谢你。
【问题讨论】:
-
欢迎使用值语义。
-
为了演示你的问题,你就不能简单的把你的代码变短吗?
Node类和那些 Set/Get Y/X 以什么方式与问题相关?
标签: c++ class pass-by-reference