使operator+成员函数返回const临时对象,则 "obj1 + obj2 = obj3" 不能通过编译,从而避免这种错误。
#include<iostream> template<typename T> class MyTest{ T m_data; public: MyTest() : m_data(){} MyTest(const T &dat) : m_data(dat){} MyTest(const MyTest &tes) : m_data(tes.m_data){} const MyTest operator+(const MyTest &tes) const{ return MyTest(m_data + tes.m_data); } //MyTest operator+(const MyTest &tes) const{ // return MyTest(m_data + tes.m_data); //} }; int main(){ MyTest<int> obj1(5), obj2(9), obj3; obj1+ obj2 = obj3; return 0; }
编译时"obj1 + obj2 = obj3"时发生错误:
ConstRet.cpp: In function ‘int main()’:
ConstRet.cpp:20:16: error: passing ‘const MyTest<int>’ as ‘this’ argument of ‘MyTest<int>& MyTest<int>::operator=(const MyTest<int>&)’ discards qualifiers [-fpermissive]
obj1+ obj2 = obj3;
^