请教,在C++语言里左值和右值分别和运算符重载的实现有什么关系?运算符重载怎么看出是哪个方式实现的?
http://blog.csdn.net/qq1449301756/article/details/47702997
你可以直接运行一下上面这段代码,监视一下内存和地址啥的。
#include "stdafx.h"
#include <iostream>
using namespace std;
#define USE_R_VAL_OPERATOR 1
class Person
{
public:
Person(){}
Person(unsigned int num) : real(num) {}
virtual void show(){ std::cout << "Show Person num:" << real << std::endl; }
#if USE_R_VAL_OPERATOR
Person Person::operator+(Person &c2)
{
Person c;
c.real = real + c2.real;
return c;
}
#else
Person& Person::operator+(Person &c2)
{
this->real = this->real + c2.real;
return *this;
}
#endif
private:
unsigned int real = 0;
};
class Student : public Person
{
public:
Student(unsigned int num) : Person(num) {}
};
class Worker : public Person
{
public:
Worker(unsigned int num) : Person(num) {}
};
class WorkStu : public Person
{
public:
WorkStu(unsigned int num) : Person(num) {}
};
void fun(Person *ptr)
{
ptr->show();
}
int _tmain(int argc, _TCHAR* argv[])
{
Person person(10);
Student student(20);
#if USE_R_VAL_OPERATOR
auto res = person + student;
// 这种是右值的运算符重载,运算后,person和student的对象都没有变化,返回值是一个临时变量(右值)
#else
auto res = person + student;
// 这种是左值的运算符重载,运算后, ‘+’前面的这个对象本身发生变化,返回值是person对象的引用
#endif
fun(&res);
cin.get();
return 0;
}