我是编程新手,基于谷歌搜索,第一次点击总是'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