c++重载并重写运算符+

c++ Overloading and overriding the operator+

本文关键字:运算符 重写 重载 c++      更新时间:2023-10-16

我有一项任务需要我完成以下任务,

Character是Digit的超类,Object是Character的超类。

  1. 重载类Character的运算符+,以便它可以添加两个Character类型的对象。

  2. 覆盖Digit类中的运算符+,以便它将两位数字的数值相加,并提供我们最终应用"模10"时得到的数字。(示例'5'+'6'='1'//5+6=11%10=1)

我试着把它们编码出来,并有不同的解决方案。我在代码中发表了评论,希望有人能在评论中回答我的问题。

class Character : public Object {
protected:
    char ch;
    char getChar() {
        return this->ch;
    }
    char setChar(char in) {
        this->ch = in;
    }
public:
    //Why must I put Character&? What is the purpose of &?
    Character operator+(const Character& in) { 
        Character temp;
        temp.ch = this->ch + in.ch;
        return temp;
    }
};
class Digit : public Character {
public:
    //Can i use the commented code instead?
    /*
    int a, b, c; 
    Digit operator+(Digit& in){
        Digit temp;
        temp.c = (in.a + in.b) % 10;
        return temp;
    }
    */
    Digit operator+(const Digit& in) {
        Digit tmp;
        //Can some one explain what is this?
        tmp.ch = (((this->ch - '0') + (in.ch - '0')) % 10) + '0'; 
        return tmp;
    }
};

//为什么必须放Character&?&的目的是什么;?

& - reference. operator+ overloading works on two arguments, first one is passed implicitly, while the second one is passed by reference

//我可以使用注释代码吗?

/*
int a, b, c; 
Digit operator+(Digit& in){
    Digit temp;
    temp.c = (in.a + in.b) % 10;
    return temp;
}
*/

您不能使用此代码。您需要传递"const",它保证了第二个参数的不变性

    //Can some one explain what is this?
    tmp.ch = (((this->ch - '0') + (in.ch - '0')) % 10) + '0';

获取数字的ascii表示,提取它的数值,添加数值并转换回sum的ascii表达。

为什么必须放置Character&?&的目的是什么这意味着参数由引用/指针获取,并且对象不会被复制。

我可以使用注释的代码吗此代码使用了未初始化的变量,因此无法正常工作。

//有人能解释一下这是什么吗ch-"0"是一个众所周知的破解方法,用于获取数字的ascii表示值

%10:

如果结果超过10,则减去10(模运算符)

'+'0':

转换为ascii表示

//Why must I put Character&? What is the purpose of &?

这导致字符通过引用传递,这是运算符重载的要求。阅读按值传递和按引用传递。


tmp.ch = (((this->ch - '0') + (in.ch - '0')) % 10) + '0'; 

当被一条线弄糊涂时,试着把它分解。我假设你可以在这行的开头跟着赋值,所以让我们看看等式后面的表达式:

(((this->ch - '0') 

从中读取字符的ASCII值。从中减去"0"的ASCII值。这是因为ascii具有升序。看见http://www.asciitable.com/并在表中查找数字。

这将为您提供一个从0到>9的整数,对应于传入的ASCII字符。

+ (in.ch - '0'))

这使用相同的技巧从传入值中提取十进制值。

 % 10) 

将0到9之间的两个数字相加可以很容易地得到一个>9的数字,该数字不能表示为单个ASCII字符。这是余数运算符,它去掉了除答案的第一位以外的所有内容,即0->9就是剩下的全部内容。

+ '0'; 

最后,它将"0"添加回生成的整数,以将其转换回ASCII。