从0开撸C++(四)——函数重载和运算符重载

往期地址:

本期主题:
c++中的函数重载和运算符重载



1.重载定义

1.1 函数重载

  • 定义: 函数重载是在一定作用域内,多个相同名称但不同参数列表的函数重载
  • 关键: 函数重载的关键是函数的参数列表——函数特征标
  • 常见举例:我们常接触到的比较典型的就是构造函数的重载
person::person()
{
    cout << "this is default constructor" << endl;
}

person::person(string name)
{
    cout << "string " << endl;
}

person::~person()
{
    cout << "this is default deconstructor" << endl;
}

int main(void)
{
    person testperson("jason");
    return 0;
}

gary@ubuntu:~/workspaces/cpp_study/2.6.operator_overload$ ./app 
string 
this is default deconstructor

//再看一个例子,对printf的重载
class printData
{
   public:
      void print(int i) {
        cout << "整数为: " << i << endl;
      }
 
      void print(double  f) {
        cout << "浮点数为: " << f << endl;
      }
 
      void print(char c[]) {
        cout << "字符串为: " << c << endl;
      }
};
 
int main(void)
{
   printData pd;
 
   // 输出整数
   pd.print(5);
   // 输出浮点数
   pd.print(500.263);
   // 输出字符串
   char c[] = "Hello C++";
   pd.print(c);
 
   return 0;
}

gary@ubuntu:~/workspaces/cpp_study/2.6.operator_overload$ ./app 
整数为: 5
浮点数为: 500.263
字符串为: Hello C++

重载的本质实际上是由编译器在实际调用时,根据实参的具体情况来判断本次调用使用哪个实际函数,这个过程被称为重载决策;

1.2 运算符重载

  • 什么是运算符
    包括加减乘除算术运算符和大于/小于/等于/不等于等关系运算符
  • 运算符重载定义
    函数重载就是在编译的时候,通过实际调用来确定用哪个实际函数,重定义函数,运算符重载相同,其实就是重定义运算符

重载的运算符是带有特殊名称的函数,函数名是由关键字 operator 和其后要重载的运算符符号构成的。

2.重载加号运算符

看一个实际的例子,用重载的加号运算符来实现向量的加法

class coordinate
{
public:
    int x;
    int y;

    coordinate();               //默认构造函数
    coordinate(int x0, int y0); //带参构造函数

    coordinate operator+(const coordinate& other);  //参数是一个其他相同类型的引用
    void print(void);
};

coordinate::coordinate()
{
    this->x = 0;
    this->y = 0;
}

coordinate::coordinate(int x0, int y0)
{
    this->x = x0;
    this->y = y0;
}

void coordinate::print(void)
{
	cout << "(" << this->x << ", " << this->y << ")" << endl;
}


coordinate coordinate::operator+(const coordinate& other)   //第一个coordinate代表返回类型,第二个coordinate代表类名,operator+就是代表要重载运算符+
{
    coordinate tmp;
    tmp.x = this->x + other.x;          //对象的属性用this传递,再加上other传递进来的属性
    tmp.y = this->y + other.y;
    return tmp;
}

int main(void)
{
    coordinate a(1, 2);
    coordinate b(2, 4);
    coordinate c;
    c = a+b;
    c.print();

    return 0;

}

gary@ubuntu:~/workspaces/cpp_study/2.6.operator_overload$ ./app 
(3, 6)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值