私はグーグル検索に基づいてプログラミングに不慣れです、最初のヒットは常に「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