《C++进阶--8.运算符重载》

c++运算符重载问题 运算符重载问题 所谓重载,就是重新赋予新的含义。函数重载是对一个已有的函数赋予新的含义,使之实现新功能。 其实运算符也可以重载,实际上,我们常常在不知不觉之中使用了运算符重载。 运算符重载的方法是定义一个重载运算符的函数,在需要执行被重载的运算符时,系统就自动调用该函数,以实现相应的运算。 也就是说,运算符重载是通过定义函数实现的。运算符重载实质上是函数的重载。 重载运算符的函数一般格式如下: 函数类型 operator 运算符名称(形参表列) { 对运算符的重载处理 } 重载小规则1 C+ 阅读详情

目录

8. 运算符重载

        8.1 加号运算符重载

        8.2 左移运算符重载

        8.3 递增运算符重载

        8.4 赋值运算符重载

        8.5 关系运算符重载

        8.6 函数调用运算符重载


8. 运算符重载

运算符重载概念:对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型

8.1 加号运算符重载

作用:实现两个自定义数据类型相加的运算

示例:

class Person {
public:
    Person() {};
    Person(int a, int b)
    {
        this->m_A = a;
        this->m_B = b;
    }
    //成员函数实现 + 号运算符重载
    Person operator+(const Person& p) {
        Person temp;
        temp.m_A = this->m_A + p.m_A;
        temp.m_B = this->m_B + p.m_B;
        return temp;
    }
​
​
public:
    int m_A;
    int m_B;
};
​
//全局函数实现 + 号运算符重载
//Person operator+(const Person& p1, const Person& p2) {
//  Person temp(0, 0);
//  temp.m_A = p1.m_A + p2.m_A;
//  temp.m_B = p1.m_B + p2.m_B;
//  return temp;
//}
​
//运算符重载 可以发生函数重载 
Person operator+(const Person& p2, int val)  
{
    Person temp;
    temp.m_A = p2.m_A + val;
    temp.m_B = p2.m_B + val;
    return temp;
}
​
void test() {
​
    Person p1(10, 10);
    Person p2(20, 20);
​
    //成员函数方式
    Person p3 = p2 + p1;  //相当于 p2.operaor+(p1)
    cout << "mA:" << p3.m_A << " mB:" << p3.m_B << endl;
​
​
    Person p4 = p3 + 10; //相当于 operator+(p3,10)
    cout << "mA:" << p4.m_A << " mB:" << p4.m_B << endl;
​
}
​
int main() {
​
    test();
​
    system("pause");
​
    return 0;
}

总结1:对于内置的数据类型的表达式的的运算符是不可能改变的,只能用于自定义数据类型

总结2:不要滥用运算符重载

8.2 左移运算符重载

作用:可以输出自定义数据类型

示例:

class Person {
    friend ostream& operator<<(ostream& out, Person& p);
​
public:
​
    Person(int a, int b)
    {
        this->m_A = a;
        this->m_B = b;
    }
​
    //成员函数 实现不了重载<<运算符,  p << cout 不是我们想要的效果
    //void operator<<(Person& p){
    //}
​
private:
    int m_A;
    int m_B;
};
​
//全局函数实现左移重载
//ostream对象只能有一个
ostream& operator<<(ostream& out, Person& p) {
    out << "a:" << p.m_A << " b:" << p.m_B;
    return out;
}
​
void test() {
​
    Person p1(10, 20);
​
    cout << p1 << "hello world" << endl; //链式编程
}
​
int main() {
​
    test();
​
    system("pause");
​
    return 0;
}

总结:重载左移运算符配合友元可以实现输出自定义数据类型

8.3 递增运算符重载

作用: 通过重载递增运算符,实现自己的整型数据

示例:

class MyInteger {
​
    friend ostream& operator<<(ostream& out, MyInteger myint);
​
public:
    MyInteger() {
        m_Num = 0;
    }
    //前置++,返回引用数据类型是为了一直对一个数据进行递增
    MyInteger& operator++() {
        //先++
        m_Num++;
        //再返回
        return *this;
    }
​
    //后置++,重载
    MyInteger operator++(int) {//int代表占位参数,可以用于区分前置和后置的运算符重载
        //先返回
        MyInteger temp = *this; //记录当前本身的值,然后让本身的值加1,但是返回的是以前的值,达到先返回后++;
        m_Num++;
        return temp;
    }
​
private:
    int m_Num;
};
​
​
ostream& operator<<(ostream& out, MyInteger myint) {
    out << myint.m_Num;
    return out;
}
​
​
//前置++ 先++ 再返回
void test01() {
    MyInteger myInt;
    cout << ++myInt << endl;
    cout << myInt << endl;
}
​
//后置++ 先返回 再++
void test02() {
​
    MyInteger myInt;
    cout << myInt++ << endl;
    cout << myInt << endl;
}
​
int main() {
​
    test01();
    //test02();
​
    system("pause");
​
    return 0;
}

总结: 前置递增返回引用,后置递增返回值

8.4 赋值运算符重载

c++编译器至少给一个类添加4个函数

  1. 默认构造函数(无参,函数体为空)

  2. 默认析构函数(无参,函数体为空)

  3. 默认拷贝构造函数,对属性进行值拷贝

  4. 赋值运算符 operator=, 对属性进行值拷贝

如果类中有属性指向堆区,做赋值操作时也会出现深浅拷贝问题

示例:

class Person
{
public:
​
    Person(int age)
    {
        //将年龄数据开辟到堆区
        m_Age = new int(age);
    }
​
    //重载赋值运算符 
    Person& operator=(Person &p)
    {
        
        //编译器提供的代码是浅拷贝,会导致堆区内容重复释放,程序崩溃
        //m_Age = p.m_Age;
​
        //提供深拷贝 解决浅拷贝的问题
        if (m_Age != NULL)
        {
            delete m_Age;
            m_Age = NULL;
        }
        m_Age = new int(*p.m_Age);
​
        //返回自身,实现连等 a=
        return *this;
    }
​
​
    ~Person()
    {
        if (m_Age != NULL)
        {
            delete m_Age;
            m_Age = NULL;
        }
    }
​
    //年龄的指针
    int *m_Age;
​
};
​
​
void test01()
{
    Person p1(18);
​
    Person p2(20);
​
    Person p3(30);
​
    p3 = p2 = p1; //赋值操作
​
    cout << "p1的年龄为:" << *p1.m_Age << endl;
​
    cout << "p2的年龄为:" << *p2.m_Age << endl;
​
    cout << "p3的年龄为:" << *p3.m_Age << endl;
}
​
int main() {
​
    test01();
​
    //int a = 10;
    //int b = 20;
    //int c = 30;
​
    //c = b = a;
    //cout << "a = " << a << endl;
    //cout << "b = " << b << endl;
    //cout << "c = " << c << endl;
​
    system("pause");
​
    return 0;
}

8.5 关系运算符重载

作用:重载关系运算符,可以让两个自定义类型对象进行对比操作

示例:

class Person
{
public:
    Person(string name, int age)
    {
        this->m_Name = name;
        this->m_Age = age;
    };
​
    bool operator==(Person & p)
    {
        if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
​
    bool operator!=(Person & p)
    {
        if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
​
    string m_Name;
    int m_Age;
};
​
void test01()
{
    //int a = 0;
    //int b = 0;
​
    Person a("孙悟空", 18);
    Person b("孙悟空", 18);
​
    if (a == b)
    {
        cout << "a和b相等" << endl;
    }
    else
    {
        cout << "a和b不相等" << endl;
    }
​
    if (a != b)
    {
        cout << "a和b不相等" << endl;
    }
    else
    {
        cout << "a和b相等" << endl;
    }
}
​
​
int main() {
​
    test01();
​
    system("pause");
​
    return 0;
}

8.6 函数调用运算符重载

  • 函数调用运算符 () 也可以重载

  • 由于重载后使用的方式非常像函数的调用,因此称为仿函数

  • 仿函数没有固定写法,非常灵活

示例:

class MyPrint
{
public:
    void operator()(string text)
    {
        cout << text << endl;
    }
​
};
void test01()
{
    //重载的()操作符 也称为仿函数
    MyPrint myFunc;
    myFunc("hello world");
}
​
​
class MyAdd
{
public:
    int operator()(int v1, int v2)
    {
        return v1 + v2;
    }
};
​
void test02()
{
    MyAdd add;
    int ret = add(10, 10);
    cout << "ret = " << ret << endl;
​
    //匿名对象调用  
    cout << "MyAdd()(100,100) = " << MyAdd()(100, 100) << endl;
}
​
int main() {
​
    test01();
    test02();
​
    system("pause");
​
    return 0;
}

H3C交换机S-MLAG实战:如何用bond4模式实现服务器高可用(附避坑指南) 本文详细介绍了H3C交换机S-MLAG技术与服务器bond4模式的实战配置,帮助实现跨设备链路聚合的服务器高可用方案。通过解析S-MLAG技术优势、bond4模式选择、关键配置步骤及常见问题排查,提供了一套完整的避坑指南和优化建议,适用于企业级网络架构的高可用需求。 阅读详情

相关推荐

重磅!AI实时读取总结微信聊天记录,附MCP协议+智能体配置教程!

【摘要】本文介绍了一套AI实时分析微信聊天记录的解决方案,通过Chatlog+Trae+MCP协议实现智能整理群聊信息。Chatlog作为开源工具本地解析微信数据,确保隐私安全;Trae提供AI分析能力,支持自然语言处理。操作步骤包括:1)下载运行Chatlog并启动HTTP服务;2)安装Trae配置MCP协议;3)创建智能体设置提示词。该方案虽需初始配置,但能有效解决群聊信息过载问题,自动提炼关键内容,避免有价值信息被淹没。文中提供了详细教程链接和网盘资源。

puyihuan的博客 1万+

2021-8-4 C++进阶学习 -> 4.5运算符重载

目录 4.5.1加号运算符重载 4.5.2左移运算符重载 4.5.3递增运算符重载 4.5.4赋值运算符重载 4.5.5关系运算符重载 4.5.6函数调用运算符重载 4.5.1加号运算符重载 加号运算符重载 1、成员函数重载+ 成员函数调用本质 Person p3 = p1.operator+(p2); Person p3 = p1 + p2; 2、全局函数重载+ Person p3 = operator+(p1, p2); Person p3 = ...

ice_cream_moon的博客 162

从内外参推导IPM变换方程及代码实现(生成AVM环视拼接图)

最近想实现AVM拼接,看了不少博客和论文,不过比较愚钝,一直没能很好理解原理,尤其是怎么在实现时把下文中Z1和Z2消除的,所以严谨的推导了一下对应的公式,如有不对,水平有限,烦请指出~IPM变换(逆透视变换),顾名思义,即将正常透视效应消除的变换,变换结果为鸟瞰图BEV(俯视图);AVM环视拼接一般是将车身前后左右的四个鱼眼相机拼接成环视图(也是俯视),其使用的单应矩阵将四个相机转到同一个俯视坐标系。

mxdsdo09的博客 4172

C++的运算符重载

1.作为新手学习C++的运算符重载,首先应该了解C++的运算符重载有何现实意义? 之前已对多态性有了相关总结,得出结论:函数重载体现出多态性。实际上,运算符重载也体现出了多态性。在C++中我们定 义的int、float、double等基本数据类型的变量后,就可以直接用“ + ”、“ -”、“ *”、“ / ”等运算符进行相关的计算,然后把得到的 计算 结果通过" ...

jacket_的博客 6万+

将AD域服务从windows server 2008 R2 迁移到windows server 2019

添加一台windows 2019 的服务器并加入现有林的域中,并将角色升级为域控制器。然后迁移FSMO角色,使其成为PDC,然后降级旧DC,并提升域和林的功能级别。最后还要说下,Server 2008 R2我们还可以删除角色并退出当前域,这里就不做操作了。2)右键 mingling.com(我的域为mingling.com)--提升域级别功能。勾选 将域控制器添加到现有域,使用域管理员将DC2加入到现有的AD域。1)打开服务器管理器---工具---AD域和信任关系。2)运行域安装服务向导,选择下一步。

lionxam的博客 3660

图像处理基础 || (一) python 读取图像的常用方式

图像的读取与保存是图像处理或计算机视觉领域中最基本的操作,python中有众多的库支持图像的读取、显示与存储,常用的库包括 matplotlib、skimage 和 Pillow 库。

weixin_40234309的博客 5689

C++ 运算符重载:成员、非成员函数重载

C++ 运算符重载运算符重载1、背景2、运算符函数重载的两种形式1、成员函数重载1、定义格式2、非成员函数重载(友元)1、定义格式3、重载原则4、参数和返回值5、成员函数重载1、双目运算符重载1、定义2、调用格式2、单目运算符重载1、定义2、调用格式6、非成员函数(友元)重载1、定义2、定义形式3、调用格式4、重载原则:+和 -运算符的重载实例++和--运算符的重载:重载输入输出操作符<< >>string类实例(重载综合说明)参考 运算符重载 1、背景 C++中标准运算符(如+、

JMW1407的博客 1万+

基于Spring Boot 3 + Vue 3 + UniApp的全栈高校社团管理小程序设计与实现

requestMatchers("/api/auth/**", "/doc.html", "/webjars/**", "/v3/api-docs/**").permitAll() // 公开接口。<u-search placeholder="搜索活动" v-model="searchKeyword" @search="loadActivities" :showAction="false"></u-search>R.success("活动创建成功") : R.error("活动创建失败");

2201_76125393的博客 368

【c++】cpp运算符重载

c++运算符重载

hutaotaotao的博客 1886

第一章:基础知识 - 概念与基础,理解什么是功耗

电源管理与功耗调优:实战项目经验分享

坚韧与专注 885

YOLO26改进105:全网首发--使用BiFPN改进特征金字塔网络

YOLOv6 v3.0在目标检测领域实现重大突破,通过改进网络架构和训练方案显著提升性能。该版本在COCO数据集上展现出优越表现:YOLOv6-N达到37.5% AP/1187 FPS,YOLOv6-S实现45.0% AP/484 FPS,均超越同类检测器。大模型YOLOv6-M/L分别达到50.0%/52.8% AP,L6版本更创下实时检测新纪录。关键技术包括RepVGGBlock、BiFusion等新型模块,通过多分支融合和高效重参数化设计提升性能。研究团队已验证各改进模块有效性,代码已开源。

AIcurator的博客 95

C++ 运算符重载

C++ 运算符重载. 我们为什么要重载运算符, 以及重载的用途以及好处.

我是小白呀的博客 7931

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

C++ 运算符重载全面解析

C++ 运算符重载全面解析

嗨,欢迎来到我的 优快云 博客小天地!一名深耕多年的技术发烧友。在这里,我将把日常工作中积累的宝贵经验,从复杂架构设计的精妙之处,到代码优化的实战技巧,毫无保留地分享给大家。 1万+

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

C++——运算符的重载

运算符重载,就是对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。让类类型的对象像基本数据类型一样去操作 例如:可以实现对象+,-* / % ==!运算符的重载实际是一种特殊的函数重载,必须定义一个函数,并告诉C++编译器,当遇到该重载的运算符时调用此函数。这个函数叫做运算符重载函数,通常为类的成员函数。定义运算符重载函数的一般格式:返回值类型 类名::operator重载的运算符(参数表) {……}operator是关键字,它与重载的运算符一起构成函数名。

weixin_59179454的博客 1万+

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

C++运算符重载详解

(类和对象)运算符重载本质还是函数调用,但C++编译器做了特殊的处理,在程序中,函数的实参书写在运算符+的两边,代替了函数名和括号的传统书写方式。好处。

qq_42757463的博客 3723

C++运算符重载

运算符重载是一种形式的C++多态,它使得对象操作更直观,本质上也是属于函数重载。实际上,我们已经在不知不觉之中使用了运算符重载。例如,加法运算符“+”可以对整数相加、也可以对string对象相加,如5+8;s1+s2;这是因为C++已经对string类重载了“+”运算符。又例如,C++对“<<”和“>>”进行了重载,用户在不同的场景下使用它们,作用是不同的。对于位运算而言,“<<”运算符是左移运算符,“>>”运算符是右移运算符。

weixin_75188368的博客 1844

Cpp实验:运算符重载

运算符重载是C++中的特殊语法,它能够让我们为自定义的类型定义运算符的行为。1. 运算符重载让我们可以为自定义类型定义类似原生数据类型的运算符。比如,我们可以通过重载“+”运算符来实现自定义类型的加法运算。2. 运算符重载遵循一些规则,比如运算符重载函数必须作为类的成员函数或全局函数,不能改变运算符的优先级和结合性,等等。3. 运算符重载可以大大简化代码,提高可读性和可维护性。通过自定义类型的运算符,我们可以直接对自定义类型进行运算操作,不再需要额外的函数调用。

lengmei1的博客 1929

8、C++运算符重载

本章内容带领大家学习C++的运算符重载,了解C++运算符重载的应用场景和书写方式。

如是牛 1590

【C++】运算符重载

像Stack这样的类,虽然也都是内置类型,但是_a指向了资源,编译器自动生成的赋值运算符重载完成的值拷贝/浅拷贝不符合我们的需求,所以需要我们自己实现深拷贝(对指向的资源也进行拷贝)。例如,对于加法运算符+,其重载函数的名称为。上面代码定义一个类A,包含一个公有成员函数add,创建对象obj,接着定义一个指向A类成员函数的指针pf,通过函数指针和.* 调用成员函数完成相加计算。来管理流的绑定关系,默认情况下,cin绑定到cout,输入时自动刷新cout,这可能影响性能,因为每次输入都要刷新输出缓冲区。

2302_81312180的博客 1375

C++运算符重载一:运算符重载、复数类CComplex、输入输出运算符重载

文章目录一、运算符重载二、复数类CComplex三、输出运算符重载 一、运算符重载 运算符重载: 使对象的运算运算表现得和编译器内置类型一样,使同一个运算符可以有不同的功能。即定义一个重载运算符的函数,使指定的运算符不仅能实现原有的功能,而且能实现在函数中指定的新的功能。 运算符重载实质上是函数的重载,重载运算符的函数一般格式如下: 函数类型 operator 运算符名称(形参表) {对运算符的重...

Rain的博客 4999

【C++之运算符重载2】矩阵相加 重载运算符 “+”、“<<”、“>>”

题目要求 有两个矩阵 a 和 b,均为2行3列。求**两个矩阵之和**。重载运算符 "+" ,使之能用于矩阵相加。如 c = a + b 。 ——谭浩强的《C++面向对象程序设计》第4章习题第4小题 在第4题的基础上,重载**流插入运算符 “...

霍喜猫的博客 6041

028-C++ 重载运算符和重载函数

接下来,我们将深入探讨更复杂的场景和高级用法,包括运算符重载的特殊情况、函数重载的限制与扩展,以及二者在实际开发中的结合与应用。运算符重载和函数重载是 C++ 的重要特性,在实际开发中,合理使用二者可以显著提高程序的灵活性和可读性,同时保持代码高度的可维护性和可扩展性。通过重载,可以为类对象自定义运算符的行为,以及定义多个具有相同名称但参数不同的函数。通过合理使用运算符重载和函数重载,可以使代码更加灵活、清晰,同时增强类设计的可扩展性和可维护性。类的成员函数也可以重载,但需要遵守相同的规则。

小宝哥Code的专栏 1767

C++类的运算符重载

C++类的运算符重载

Jasmine-Lily的博客 3811
上一篇: 《C++进阶--7.友元》
下一篇: 《C++进阶--9.继承》
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序猿!=程序员

感谢来过,感谢有你!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值