⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 reflexivityinoverloading.cpp

📁 ThinkingC++中文版
💻 CPP
字号:
//: C12:ReflexivityInOverloading.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
class Number {
  int i;
public:
  Number(int ii = 0) : i(ii) //具有把int类型转换成Number类型的功能
  {}
  const Number operator+(const Number& n) const //requires that the left operand already be a Number object. 
  {
    return Number(i + n.i);
  }
  friend const Number operator-(const Number&, const Number&);
};

const Number  operator-(const Number& n1, const Number& n2) 
{
    return Number(n1.i - n2.i);
}

void main() 
{
  Number a(47), b(11);
  a + b; // OK call: a.operator+(b);
  a + 1; // 2nd arg converted to Number	call: a.operator+(Number(1))
//!  1 + a; // Wrong! 1st arg not of type Number
  a - b; // OK call: operator-(a,b)
  a - 1; // 2nd arg converted to Number.call: operator-(a,Number(1));
  1 - a; // 1st arg converted to Number.call: operator-(Number(1),a);
  1 - 1;
//Fortunately, the compiler will not take 1 – 1 and convert both arguments to Number objects and then call operator–. 
//That would mean that existing C code might suddenly start to work differently. 
//The compiler matches the “simplest” possibility first, which is the built-in operator for the expression 1 – 1.

} ///:~

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -