【发布时间】:2015-11-19 16:45:08
【问题描述】:
我有一个任务要求我做以下事情,
Character 是 Digit 的超类,Object 是 Character 的超类。
为类Character重载运算符+,使其可以添加两个Character类型的对象。
重写 Digit 类中的运算符 +,以便它添加两个数字的数值并传递我们最终应用“模 10”时得到的数字。 (例如“5”+“6”=“1”//5+6=11%10=1)
我试图将它们编码出来并有不同的解决方案。我在我的代码中做了cmets,希望有人能在cmets中回答我的问题。
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;
}
};
【问题讨论】:
-
您应该在每个
operator+函数签名的)之后再添加一个const。答案解释了为什么第二个参数必须是const&,但第一个参数也必须是 const。Digit*的隐含第一个参数(变为this)通过使用const制成Digit const* -
作业显示“覆盖”。我无法读懂讲师的想法,但通常“覆盖”意味着您要覆盖的函数必须已声明为
virtual,除了添加该关键字之外,这给所有这一切增加了一些复杂性。所以最好的猜测是,讲师使用的术语很草率,但也许作业更难。
标签: c++ inheritance operator-overloading overriding