class Rational { public: Rational(int numerator = 0, int denominator = 1) : n(numerator), d(denominator) { printf("Rational Constructor\n"); } ~Rational() { printf("Rational Destructor\n"); } Rational(const Rational& rhs) { this->d = rhs.d; this->n = rhs.n; printf("Rational Copy Constructor\n"); } private: int n, d; friend const Rational operator*(const Rational& lhs, const Rational& rhs); };
Rational的*運算符能夠這樣重載:函數
const Rational operator*(const Rational& lhs, const Rational& rhs) { Rational tmp(lhs.n * rhs.n, lhs.d * rhs.d); return tmp; }
可是不能夠這樣重載:【區別在於一個&】優化
const Rational& operator*(const Rational& lhs, const Rational& rhs) { Rational tmp(lhs.n * rhs.n, lhs.d * rhs.d); return tmp; }
當這樣去使用:this
Rational x(1, 2), y(2, 3); Rational z = x * y;
第一種方法能夠獲得正確的結果,由於會調用Rational的拷貝構造函數將tmp賦給z,可是第二種方法返回的是tmp的引用,在函數退出前,tmp就被銷燬了,因此這樣作是不對的。spa
不過,第一種方法雖然功能上沒有問題,可是效率上有所欠缺,由於調用了三次構造函數,一次複製構造函數,一次析構函數code
Rational Constructor
Rational Constructor
Rational Constructor
Rational Copy Constructor
Rational Destructor
能夠進行返回值優化以下:blog
const Rational operator*(const Rational& lhs, const Rational& rhs) { return Rational(lhs.n * rhs.n, lhs.d * rhs.d); }
Rational Constructor
Rational Constructor
Rational Constructor
優化以後少調用了一次複製構造函數和析構函數io
完整代碼以下:class
#include <stdio.h> class Rational { public: Rational(int numerator = 0, int denominator = 1) : n(numerator), d(denominator) { printf("Rational Constructor\n"); } ~Rational() { printf("Rational Destructor\n"); } Rational(const Rational& rhs) { this->d = rhs.d; this->n = rhs.n; printf("Rational Copy Constructor\n"); } private: int n, d; friend const Rational operator*(const Rational& lhs, const Rational& rhs); }; const Rational operator*(const Rational& lhs, const Rational& rhs) { return Rational(lhs.n * rhs.n, lhs.d * rhs.d); } int main() { Rational x(1, 2), y(2, 3); Rational z = x * y; return 0; }