繁体   English   中英

名称隐藏和访问基类的非虚拟功能(语法)

[英]Name hiding and access base class' non-virtual function (syntax)

在下面的代码中:

#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,没关系,两个标准似乎都相同)中,此语法在哪里定义?

我根本不知道这是不可能的,那是我第一次看到这样的语法(第一次在这里看到: 为什么我不能在下面的代码中访问A类函数?

是的,这是名字隐藏。 因此它不是重载(也不是覆盖)。 N3485 13.2 Declaration matching13.2 Declaration matching N3485了说明。

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
}

--end示例]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM