对象的赋值运算符

时间:2013-03-20 13:14:42

标签: c++ object pointers variable-assignment operator-keyword

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

2 个答案:

答案 0 :(得分:0)

您所看到的是“运营商超载”#39;在此技术中,您为现有运算符定义新行为,在这种情况下,它是&#39; =&#39;。基本上,当在main()中调用此运算符时,它会使用它的右侧操作数并将其成员值分配给左侧操作数的成员。

答案 1 :(得分:0)

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

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

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

相关问题