2013-04-30 22 views
0

在下面的代碼:名字隱藏和訪問基類的非虛擬函數(語法)

#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?

+0

'13.2 n3337宣言matching'爲您提供了這方面的一個明顯的例子。甚至N3465當前的WD在13.2 – 2013-04-30 08:45:00

回答

1

是的,它是名稱隱藏。因此它不是超載(而不是壓倒性的)。部分13.2 Declaration matchingN3485解釋了這一點。

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示例]

相關問題