派生类中的重载运算符

Overloaded operator in derived class

本文关键字:重载 运算符 派生      更新时间:2023-10-16

我正在研究Lafore对C++书的第4次编辑,我遇到了这个问题。

我有这两个类,CountDn 派生自计数器。在 CountDn 中,我想重载递减运算符的前缀以及递增和递减的后缀。

它适用于所有运算符,除非我尝试执行++c11.

我从编译器收到这些错误:

50:10:错误:"运算符++"不匹配(操作数类型为"CountDn"(

50:10:注:候选人是:

41:13:注意:CountDn

CountDn::operator++(int(

41:13:注意:候选人期望 1 个参数, 0 提供

即使get_count()工作正常,我不明白为什么前缀运算符不起作用。

我的想法是,如果 CounterDn 类派生自 Counter 所有公共函数都应该是可访问的。我可以修改什么,以便更好地理解这个问题的解决方案?

#include <iostream>
using namespace std;
class Counter{
protected:
unsigned int count;                //count
public:
Counter() : count(0)               //constructor, no args
{  }
Counter(int c) : count(c)          //constructor, one arg
{  }
unsigned int get_count() const     //return count
{
return count;
}
Counter operator ++ ()             //incr count (prefix)
{
return Counter(++count);
}
};

class CountDn : public Counter{
public:
CountDn() : Counter()              //constructor, no args
{ }
CountDn(int c): Counter(c)       //constructor, 1 arg
{ }
CountDn operator -- ()             //decr count (prefix)
{
return CountDn(--count);
}
CountDn operator --(int){
return CountDn(count --);
}
CountDn operator ++(int)
{
return CountDn(count++);
}
};
int main() {
CountDn c1(10),c2;
c2 = ++c1;
cout << c1.get_count() << endl;
return 0;
}

operator++()operator++(int)operator++函数的两个重载。

当编译器在派生类中看到operator++(int)函数时,它不会查找函数的其他重载。因此,在尝试编译该行时找不到operator++()

c2 = ++c1;

因此,无法从基类中找到预递增运算符。可以使用using声明将基类中的预增量重载引入派生类。

class CountDn : public Counter{
public:
using Counter::operator++;
CountDn() : Counter()              //constructor, no args
{ }
CountDn(int c): Counter(c)       //constructor, 1 arg
{ }
CountDn operator -- ()             //decr count (prefix)
{
return CountDn(--count);
}
CountDn operator --(int){
return CountDn(count --);
}
CountDn operator ++(int)
{
return CountDn(count++);
}
};

现在,operator++的两个重载都可用于CountDn对象。

但是,以下仍然是个问题

c2 = ++c1;

因为前递增运算符返回的是Counter对象,而不是CountDn对象。您可以使用:

++c1;
c2 = c1;

来解决这个问题。

CountDn operator ++(int) // For Postfix operator
{
return CountDn(count++);
}
CountDn operator ++() // For prefix operator
{
return CountDn(count++);
}

添加版本前缀运算符不带参数和后缀运算符不带参数。您已在 main 函数中使用了前缀运算符,因此需要添加 without 参数函数。