C++每日一练(重载)

本文为博主原创文章,未经博主允许不得转载。

https://blog.csdn.net/lxy_2011/article/details/52638634

一、今日课题

1.函数重载

2.运算符重载

 

二、实战演练

1.函数重载


  When two or more different declarations are specified for a single name in the same scope,  that name is said to overloaded.  By extension, two declarations in the same scope that declare the same name but with different types are called overloaded declarations. Only function declarations can be overloaded; object and type declarations cannot be overloaded. ——摘自《ANSI C++ Standard. P290》


1)有何用?

减少了函数名的数量;避免了名字空间的污染;增强程序的可读性。   

2)怎么用?

 


根据函数名确定候选函数集
从候选函数集中选择可用函数集合
从可用函数集中确定最佳函数,或由于模棱两可返回错误

 


2.运算符重载


  运算符重载是对已有的运算符赋予多重含义,使同一个运算符作用域不同类型的数据导致不同行为的发生。


1)有何用?

假如我们建立两个复数,并用”+”运算符让它们直接相加:

1 Complex com1(10,10),com2(20,20),sum;
2 sum=com1+com2;

那么会提示没有与这些操作数匹配的 “+” 运算符的错误。这是因为Complex类类型不是预定义类型,系统没用对该类型的数据进行加法运算符函数的重载。C++就为运算符重载提供了一种方法,即运算符重载函数。其函数名字规定为operator后紧跟重载运算符。比如:operator+(),operator*()等。

2)怎么用?
 

#include 

using namespace std;

class Complex
{
public:
    double real, imag;
    Complex(double real = 0, double imag = 0)
    {
        this->real = real;
        this->imag = imag;
    }
};

Complex operator +(Complex com1, Complex com2)
{
    return Complex(com1.real + com2.real, com1.imag + com2.imag);
}

int main()
{
    Complex com1(10, 10), com2(20, 20), sum;
    sum = com1 + com2;
    cout << "sum的实数部分为:" << sum.real << endl;
    cout << "sum的虚数部分为:" << sum.imag << "i" << endl;

    system("pause");
    return 0;
}

 

你可能感兴趣的:(C++)