【问题标题】:Name hiding and access base class' non-virtual function (syntax)名称隐藏和访问基类的非虚函数(语法)
【发布时间】:2013-04-30 08:41:37
【问题描述】:

在以下代码中:

#include <iostream>

class A
{
public:
    void f( float x ) { std::cout << 1; }
    void g() { std::cout << 11; }
};

class B : public A
{
public:
    void f( char x ) { std::cout << 2; }
    void g() { std::cout << 22; }
};

int main()
{
    B b;
    b.A::f( 0 );
    b.A::g();

    return 0;
}

这个名字不是隐藏了吗?而这种语法在标准中定义在哪里(C++11或C++03,没关系,这两个标准似乎都是一样的)?

我完全不知道这是可能的,这是我第一次看到这样的语法(第一次在这里看到它:why cant i access class A function in following code?

【问题讨论】:

  • 13.2 Declaration matching of n3337 为您提供了一个明确的例子。甚至 N3465 Current WD 也有它在 13.2

标签: c++ syntax name-hiding


【解决方案1】:

是的,它是隐藏名称。因此它不是重载(而不是覆盖)。 N3485 中的 13.2 Declaration matching 部分对此进行了解释。

13.2 Declaration matching

 1   Two function declarations of the same name refer to the same function if they are in
the same scope and have equivalent parameter declarations (13.1). A function member of
a derived class is not in the same scope as a function member of the same name in a base class. 

[ Example:


struct B {
int f(int);
};

struct D : B {
int f(const char*);
};
Here D::f(const char*) hides B::f(int) rather than overloading it.
void h(D* pd) {
pd->f(1); // error:
// D::f(const char*) hides B::f(int)
pd->B::f(1); // OK
pd->f("Ben"); // OK, calls D::f
}

--结束示例]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 2011-08-15
    • 2017-10-27
    • 1970-01-01
    • 2013-11-13
    • 2021-10-31
    相关资源
    最近更新 更多