今天看Effective C++ 说道等号重载的事,心里一直有疑惑,这些运算符重载都是怎么实现的。在学C++的时候只是草草的看过这部分内容,没有真正自己使用过,对于等号如何操作私有成员一直有疑问,今天试了一下,哎,还真对得起咱这张脸。。。
#include <iostream>
class A
{
public:
A(void) : mVal(0)
{
}
A(int v) : mVal(v)
{
}
A(const A &obj)
{
mVal = obj.mVal;
}
~A(void){}
A& operator = (const A& R)
{
mVal = R.mVal;
return *this;
}
void equal(const A &R)
{
mVal = R.mVal;
}
void set(int v)
{
mVal = v;
}
int get(void)
{
return mVal;
}
private:
int mVal;
};
int main(void)
{
std::cout<<"Hello assign operator"<<std::endl;
A obj1(1);
A obj2(2);
std::cout<<"The value of obj1 is "<<obj1.get()<<std::endl;
std::cout<<"The value of obj2 is "<<obj2.get()<<std::endl;
std::cout<<"Do assignment"<<std::endl;
obj2 = obj1;
std::cout<<"The value of obj2 is "<<obj2.get()<<std::endl;
std::cout<<"Test copy constructor"<<std::endl;
A obj3(obj2);
std::cout<<"The value of obj3 is "<<obj3.get()<<std::endl;
std::cout<<"Test equal method"<<std::endl;
A obj4(4);
obj4.equal(obj1);
std::cout<<"The value of obj4 is "<<obj4.get()<<std::endl;
return 0;
}
原来等号可以直接操作私有成员。
事实上,复制构造函数也可以操作私有成员。。。。。
我弱爆了。。。
事实上,只要参数类型是自身的类型,就可以操作私有成员。。
下面是程序的输出
Hello assign operator
The value of obj1 is 1
The value of obj2 is 2
Do assignment
The value of obj2 is 1
Test copy constructor
The value of obj3 is 1
Test equal method
The value of obj4 is 1