0

我是编程新手,基于谷歌搜索,第一次点击总是'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 &copy         );
  wood  & operator=(const wood * const &copy );
  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 
4

2 回答 2

0

您正在查看的是“操作员重载”。在此技术中,您为现有运算符定义新行为,在本例中为“=”。基本上,当在 main() 中调用此运算符时,它会获取右侧操作数并将其成员值分配给左侧操作数的成员。

于 2013-03-20T13:27:30.777 回答
0

正如您所指出的,p_y = p_x;这只是一个简单的指针赋值。这是因为您重载了赋值运算符 for wood,而不是 for wood*

更改p_y = p_x;*p_y = *p_x;

您可以实现一个免费函数来重载operator=for wood*,但我认为这不是一个好主意。

于 2013-03-20T13:27:53.093 回答