我是新手编程,基于谷歌搜索,第一次命中总是'stackoverflow', 它一直很有帮助。我没有得到这部分的答案。它是一个简单的代码,我 一直在尝试学习赋值操作符如何处理对象。我已经看了一些 书,没有例子。对象的赋值运算符
// wood.h
using namespace std;
///#include <cstdio>
//#include <cstdlib>
//#include <iostream>
//#include <string>
class wood {
public :
wood (void);
wood (string type, string color) ;
void display(void);`
wood & operator=(const wood © );
wood & operator=(const wood * const ©);
private :
string m_color;
string m_name;
};
// wood.cc
wood:: wood (string name, string color) {
m_name = name;
m_color = color;
}
wood & wood::operator=(const wood &from) {`
cout << "calling assignment construction of" << from.m_name << endl;
m_name = from.m_name;
m_color = from.m_color;
return *this;
}
void wood::display (void) {`
cout << "name: " << m_name << " color: " << m_color << endl;
}
// test_wood.cc
int main()
{
wood *p_x, *p_y;`
wood a("abc", "blue");
wood b("def", "red");
a.display();
b.display();
b = a; // calls assignment operator, as I expected`
a.display();`
b.display();`
p_x = new wood ("xyz", "white");
p_y = new wood ("pqr", "black");
p_x->display();`
p_y->display();`
p_y = p_x; // Here it doesn't call assignment operator, Why?
// It does only pointer assignement, p_y original pointer goes into ether.
p_x->display();`
p_y->display();`
printf("p_x:%p, p_y:%p \n", p_x, p_y);
return 0;
}
//output:
name: abc color: blue
name: def color: red
calling assignment construction abc
name: abc color: blue
name: abc color: blue
name: xyz color: white
name: pqr color: black
name: xyz color: white
name: xyz color: white
p_x:0x9be4068, p_y:0x9be4068
如果您是编程新手,您所查看的代码对您而言有点过分,IMO。他们正在做的是分配操作员的操作员重载。它所做的是通过指定木材的名称和颜色来覆盖“=”的工作方式。但默认情况下,它只会分配对象的地址。 – chuthan20 2013-03-20 13:19:28