c++ - 我的编译器挑战了基本的 C++ 继承?

标签 c++ gcc

#include <iostream>

class Base
{
public:
    virtual void ok( float k ){ std::cout<< "ok..." << k; }
    virtual float ok(){ std::cout<< "ok..."; return 42.0f; }
};

class Test : public Base
{
public:
    void ok( float k ) { std::cout<< "OK! " << k; }
    //float ok() { std::cout << "OK!"; return 42; }
};

int main()
{
    Test test;
    float k= test.ok(); 
    return 0;
}

在 GCC 4.4 下编译:

hello_world.cpp: In function `int main()`:
hello_world.cpp:28: erreur: no matching function for call to `Test::ok()`
hello_world.cpp:19: note: candidats sont: virtual void Test::ok(float)

我不明白为什么 Base 中定义的 float ok() 无法被测试用户访问,即使它公开继承自它。我试过使用指向基类的指针,它确实可以编译。取消注释 float ok() 的测试实现也有效。

它是一个错误的编译器吗?我怀疑与名称屏蔽有关的问题,但我一点也不确定。

最佳答案

这叫做名称隐藏,任何派生类的字段都会隐藏所有基类中同名的所有重载字段。要使该方法在 Test 中可用,请添加 using 指令,即

using Base::ok;

测试范围内的某处。参见 this for more information .

关于c++ - 我的编译器挑战了基本的 C++ 继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6663811/

相关文章:

c++ - 多个连接字符串的同步模式匹配算法

c++ - 模板类中函数的多重定义

c - 在 C 中使用宏和 # 运算符打印空格

gcc - 让 GCC 优化手工 assembly

c++ - g++ 编译器 : compilation terminated

c++ - map 和 openMP 并行调度

c++ - 开始学习 OpenGL,需要帮助解决这个问题

c++ - ubuntu 上缺少 QWT 安装文件

macos - 无法使用 Homebrew 软件安装 gcc48

c - __STDC_IEC_559__ 与现代 C 编译器的状态