为什么编译时没有警告?

struct A{
    virtual void get(int const x) = 0;
};

struct B : public A{
    virtual void get(int x) override{

    }
};

int main(int argc, char *argv[]){
    B b;
    b.get(6);

    return 0;
}


这是输出:

g++ -std=c++11 -Wall ./x.cc
clang -std=c++11 -Wall ./x.cc -lstdc++


如果添加-Wextra,则会收到有关未使用的函数参数的消息,但有关const的消息仍然不多。

最佳答案

方法签名完全相同,因此代码没有问题。如果它们不匹配,您将期望出现错误,而不是警告。

为什么签名相同?因为顶级const被忽略1。这三个是重复的声明:

void foo(const int); // declaration of foo(int)
void foo(int const); // re-declaration of foo(int)
void foo(int);       // re-declaration of foo(int)


最好从函数声明中省略顶级const,因为它们充其量是令人困惑的。您可以将函数定义中的const用作实现细节,就像您不希望修改任何局部变量const一样,可以使用相同的方法。

void foo(const int n)
{
  // n is const here. I know that is shouldn't be changed so I enforce it.
}




1另请参见:What are top-level const qualifiers?

关于c++ - 当方法重写并省略const时,gcc编译器不显示警告,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31941699/

10-12 12:41
查看更多