LoveBeyond

C++中的返回值优化

```1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 // C++ Return Value Optimization // 作者：代码疯子 // 博客：http://www.programlife.net/ #include <iostream> using namespace std;   class Rational { public: Rational(int numerator = 0, int denominator = 1) : n(numerator), d(denominator) { cout << "Constructor Called..." << endl; } ~Rational() { cout << "Destructor Called..." << endl; } Rational(const Rational& rhs) { this->d = rhs.d; this->n = rhs.n; cout << "Copy Constructor Called..." << endl; } int numerator() const { return n; } int denominator() const { return d; } private: int n, d; };   //const Rational operator*(const Rational& lhs, // const Rational& rhs) //{ // return Rational(lhs.numerator() * rhs.numerator(), // lhs.denominator() * rhs.denominator()); //}   const Rational operator*(const Rational& lhs, const Rational& rhs) { cout << "----------- Enter operator* -----------" << endl; Rational tmp(lhs.numerator() * rhs.numerator(), lhs.denominator() * rhs.denominator()); cout << "----------- Leave operator* -----------" << endl; return tmp; }   int main(int argc, char **argv) { Rational x(1, 5), y(2, 9); Rational z = x * y; cout << "calc result: " << z.numerator() << "/" << z.denominator() << endl;   return 0; }```

```1 2 3 4 5 6 const Rational operator*(const Rational& lhs, const Rational& rhs) { return Rational(lhs.numerator() * rhs.numerator(), lhs.denominator() * rhs.denominator()); }```

posted on 2011-10-12 18:40 LoveBeyond 阅读(3300) 评论(7)  编辑 收藏 引用

 < 2011年10月 >
2526272829301
2345678
9101112131415
16171819202122
23242526272829
303112345

• 随笔 - 26
• 文章 - 0
• 评论 - 21
• 引用 - 0

•

• 积分 - 52738
• 排名 - 413