以下面一段代码为例:
template<class Derived>
struct base {
Derived operator++(int){
auto tmp = static_cast<Derived &>(*this);
++static_cast<Derived &>(*this);
return tmp;
}
};
struct der : public base<der> {
der &operator++(){
return *this;
}
};
int main(){
der d;
d++;/// <<< compilation error here
}
我从编译器中得到以下错误:
error: no 'operator++(int)' declared for postfix '++' [-fpermissive]
为什么我的后缀运算符对编译器不可见?它包含某种错误还是我不知道的 C++ 功能?是否可以修复此代码,以便后缀 operator++
能够按预期工作?
最佳答案
您的两个函数同名,operator++
。它只是与用标识符命名的函数的拼写不同。类成员查找的规则是,默认情况下,如果在派生类中找到具有该名称的成员,则不检查基类。派生成员“隐藏”了基础成员。
避免隐藏具有不同签名的基类函数并允许重载决策选择最佳函数的常用方法是使用 using 声明:
struct der : public base<der> {
der &operator++(){
return *this;
}
using base<der>::operator++;
};
关于c++ - 来自 CRTP 基础的 Operator++ 对编译器不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55212211/