05-C++-operator

operator可以作为类转换函数或在类中作重载运行符下面对此两种使用场景进行描述

1、operator作类的转换函数

cpp 复制代码
#include <iostream>

using namespace std;

class my_class
{
public:
    operator int()//定义了一个将类转化为int的转换函数
    {
        return 1;
    }
};

int main()
{
    my_class a;
    int i_a = (int)a;//显式的转换
	cout <<"i_a:"<< i_a << endl;
    cout <<"a:"<< a << endl;//隐式的转换

    return 0;
}

运行结果

cpp 复制代码
i_a:1
a:1

2、operator在类中重载运算符

cpp 复制代码
#include <iostream>

using namespace std;

class DemoClass
{
public:
    DemoClass() {}
    DemoClass(int a, double b):a_(a),b_(b){}
    ~DemoClass(){}

    int get_a() { return a_; }
    double get_b() { return b_; }

    DemoClass operator+(const DemoClass &adder) const//以成员函数方式重载+
    {
        DemoClass sum;
        sum.a_ = a_ + adder.a_;
        sum.b_ = b_ + adder.b_;
        return sum;
    }

    friend DemoClass operator-(const DemoClass &A,const DemoClass &B)//以友元方式重载-
    {
        DemoClass diff;
        diff.a_ = A.a_ - B.a_;
        diff.b_ = A.b_ - B.b_;
        return diff;
    }

private:
    int a_;
    double b_;
};


int main()
{
    DemoClass A(1, 1.1);
    DemoClass B(2, 2.2);
    DemoClass sum = A + B;
    DemoClass diff = A - B;
    cout <<"A+B:"<< sum.get_a() << "   " << sum.get_b() << endl;
    cout <<"A-B:"<<diff.get_a() << "   " << diff.get_b() << endl;

    return 0;
}

运行结果

cpp 复制代码
A+B:3   3.3
A-B:-1   -1.1
相关推荐
Minecraft红客31 分钟前
C++小游戏荒芜的城堡
c++·游戏·娱乐
scx201310047 小时前
20250814 最小生成树和重构树总结
c++·算法·最小生成树·重构树
weixin_307779138 小时前
VS Code配置MinGW64编译SQLite3库
开发语言·数据库·c++·vscode·算法
励志不掉头发的内向程序员9 小时前
STL库——string(类函数学习)
开发语言·c++
浮灯Foden12 小时前
算法-每日一题(DAY13)两数之和
开发语言·数据结构·c++·算法·leetcode·面试·散列表
淡海水12 小时前
【原理】Struct 和 Class 辨析
开发语言·c++·c#·struct·class
青草地溪水旁13 小时前
UML函数原型中stereotype的含义,有啥用?
c++·uml
青草地溪水旁13 小时前
UML函数原型中guard的含义,有啥用?
c++·uml
光头闪亮亮16 小时前
C++凡人修仙法典 - 宗门版-上
c++
光头闪亮亮16 小时前
C++凡人修仙法典 - 宗门版-下
c++