栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++之运算符重载(8)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++之运算符重载(8)

顾名思义,重载便是重新赋予新的含义。

运算符重载的方法:定义一个重载运算符的函数,在需要执行被重载的运算符时,系统就自动调用该函数,即本质上是通过定义函数来实现的。

重载运算符的函数一般格式为: 函数类型 operator 运算符名称 (形参表列){对运算符的重载处理}

例如: Complex operator+ (Complex& c1,Complex& c2);

以下运算符不能重载:

. (成员访问运算符)

.* (成员指针访问运算符)

:: (域运算符)

sizeof (长度运算符)

?: (条件运算符)

注意:

1.重载不能改变运算符操作数的个数、优先级、结合性

2.重载的运算符必须与自定义类型的对象一起使用,其参数至少应有一个是类对象

3.用于类对象的运算符一般必须重载,运算符“=”和“&”不必用户重载

a. =可以用于每一个类对象,可以利用它在同类对象之间相互赋值

b. &可返回类对象在内存中的起始地址

4. 运算符重载函数可以是类的成员函数、类的友元函数、普通函数

一般将单目运算符重载为成员函数,将双目运算符重载为友元函数

运算符重载函数作为类友元函数

#include 
using namespace std;

class Complex {
public:
    Complex() { real = 0; img = 0; }
    Complex(double r, double i) { real = r; img = i; }
    friend Complex operator + (Complex& c1, Complex& c2);
    void display();
private:
    double real;
    double img;
};

Complex operator+(Complex& c1, Complex& c2)
{
    return Complex(c1.real + c2.real, c1.img + c2.img);
}

void Complex::display()
{
    cout << "c3=" << real << "+" << img<<"i";
}
int main()
{
    Complex c1(3, 5), c2(2, 5), c3;
    c3 = c1 + c2;
    c3.display();
}

若运算符重载函数不是Complex类的友元函数,它就没有权利访问Complex类的私有成员。

运算符重载函数作为类的成员函数

#include 
using namespace std;
class Time {
public:
    Time() { minute = 0; sec = 0; }
    Time(int m, int s) { minute = m; sec = s; }
    Time operator++();
    void display() { cout << minute << ":" << sec << endl; }
private:
    int minute;
    int sec;
};

Time Time::operator++()
{
    if (++sec >= 60)
    {
        sec -= 60;
        minute += 1;
    }
    return *this;
}

int main()
{
    Time time1(34,0);
    for (int i = 0; i < 61; i++)
    {
        ++time1;
        time1.display();
    }
    std::cout << "Hello World!n";
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/928883.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号