Binsinc 2020-11-01 11:18 采纳率: 100%
浏览 148
已采纳

c++中operater的应用,怎么

大佬们,这几天在学c++的operater的应用,但是看了视频还有搜了一些问答还是不知道这个的用法,我看了一个视频的应用,大佬们能帮我解释这些代码中operater是什么意思么。

#pragma once
#ifndef INTEGER_H
#define INTEGER_H
class Integer
{public:
    Integer();
    Integer(int value) :m_value(value) {};
    ~Integer();
    Integer operator + (Integer other);//这个地方我就蒙蔽了,括号里面的Integer 和other不懂。
    int Intvalue() {
        return m_value;
    }
private:
    int m_value;


};


#endif // !INTEGER_H

#include "Integer.h"
Integer::Integer()
{
}
Integer::~Integer()
{
}
Integer Integer::operator+(Integer other) {
    Integer result(this->m_value + other.m_value);//这里也是。视频的说是重载+号,也不懂。。
    return result;
}
#include <iostream>
#include"Integer.h"
using namespace std;
void Test();
void Test() {
    Integer int1(10), int2(10), int3;
    int3 = int1 + int2;
    cout << int3.Intvalue();
}
int main() {
    Test();
    return 0;
}
  • 写回答

1条回答 默认 最新

  • qq_34449603 2020-11-02 04:06
    关注

    1.
    Integer operator + (Integer other);这是一个+运算符重载函数。
    operator + 你可以整体看做是一个函数,
    函数的名称为:+,被operator修饰表示是运算符重载函数。
    函数的参数为:Integer类的实例化对象other,
    函数的返回值为:Integer类的对象。
    即: Integer +(Integer other){ ....; return 一个Integer对象;}

    2.
    Integer int1(10), int2(10), int3;
    int3 = int1 + int2;
    这里可以这样理解:
    对象int1调用重载函数+,传入的参数为对象int2
    即:int1.+(int2); //这个是对象int1在调用函数+,函数内部的this指针当然是int1对象的起始地址。

    Integer Integer::operator+(Integer other) {
        Integer result(this->m_value + other.m_value);
                //当int1对象调用+函数,即:int1.+(int2)时,在+函数内部,
                //other即是int2对象,this即是int1对象指针。
    
                //这里示例化类Integer的对象result会调用构造函数,传入参数的是
                //this->m_value + other.m_value,即int1.m_value+int2.m_value。
    
         return result;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?