派生类中的重载运算符
Overloaded operator in derived class
我正在研究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 参数函数。
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 myVector 类中重载运算符 + 时出错
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 如何在 cpp 中重载运算符 +=?
- C++ 如何重载 [] 运算符并进行函数调用
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 重载运算符有地址吗?
- 如何迭代重载运算符 [] 的类?
- 重载运算符与添加问题
- 模板基类中的重载运算符
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- 重载运算符<<采用谷歌 C++ 风格
- C++ 如何正确重载 + 运算符
- cout (<<) 重载运算符不打印减去的矩阵
- 如何在 c++ 中重载运算符 + 以便能够 whrite c_str = "smth" + c_str;
- 重载运算符*以获取对另一个类的实例的引用