簡體   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