技术开发 频道

C++中利用构造函数与无名对象简化运算符重载函数


【IT168技术文档】

  在完整描述思想之前,我们先看一下如下的例子,这个例子中的加运算符重载是以非成员函数的方式出现的:
#include <iostream> using namespace std; class Test { public: Test(int a) { Test::a = a; } friend Test operator + (Test&,int); public: int a; }; Test operator + (Test &temp1,int temp2) { Test result(temp1.a + temp2); return result; } int main() { Test a(100); a = a + 10;//正确 a = 10 + a;//错误 cout<<a.a<<endl; system("pause"); }
  上面的代码是一个自定义类对象与内置整型对象相加的例子,但错误行让我们猛然感觉很诧异,但仔细看看的确也在情理中,参数顺序改变后c++无法识别可供使用的运算符重载函数了。

  我们为了适应顺序问题不得不多加一个几乎一样的运算符重载函数。

  代码如下:
#include <iostream> using namespace std; class Test { public: Test(int a) { Test::a = a; } friend Test operator + (Test&,int); friend inline Test operator + (Test&,int); public: int a; }; Test operator + (Test &temp1,int temp2) { Test result(temp1.a + temp2); return result; } inline Test operator + (int temp1,Test &temp2)//利用内联函数的定义提高效率 { return temp2+temp1; } int main() { Test a(100); a = a + 10;//正确 a = 10 + a;//正确 cout<<a.a<<endl; system("pause"); }

0
相关文章