問題描述
這可能是一個菜鳥問題,抱歉.我最近在嘗試處理 C++ 中的一些高級內(nèi)容、函數(shù)重載和繼承時遇到了一個奇怪的問題.
This is possibly a noob question, sorry about that. I faced with a weird issue recently when trying to mess around with some high level stuff in c++, function overloading and inheritance.
我舉一個簡單的例子,只是為了說明問題;
I'll show a simple example, just to demonstrate the problem;
有兩個類,classA
和classB
,如下所示;
There are two classes, classA
and classB
, as below;
class classA{
public:
void func(char[]){};
};
class classB:public classA{
public:
void func(int){};
};
據(jù)我所知 classB
現(xiàn)在應該擁有兩個 func(..)
函數(shù),由于不同的參數(shù)而重載.
According to what i know classB
should now posses two func(..)
functions, overloaded due to different arguments.
但是當在主方法中嘗試這個時;
But when trying this in the main method;
int main(){
int a;
char b[20];
classB objB;
objB.func(a); //this one is fine
objB.func(b); //here's the problem!
return 0;
}
它給出錯誤,因為方法 void func(char[]){};
位于超類 classA
中,在派生類中不可見,classB
.
It gives errors as the method void func(char[]){};
which is in the super class, classA
, is not visible int the derived class, classB
.
我怎樣才能克服這個問題?這不是 C++ 中的重載方式嗎?我是 C++ 新手,但在 Java 中,我知道我可以使用這樣的東西.
How can I overcome this? isn't this how overloading works in c++? I'm new to c++ but in Java, i know I can make use of something like this.
雖然我已經(jīng)找到了這個線程,它詢問了類似的問題,我認為這兩種情況是不同的.
Though I've already found this thread which asks about a similar issues, I think the two cases are different.
推薦答案
您只需要一個 using
:
class classB:public classA{
public:
using classA::func;
void func(int){};
};
它不會在基類中搜索 func
,因為它已經(jīng)在派生類中找到了.using
語句將另一個重載帶入同一作用域,以便它可以參與重載解析.
It doesn't search the base class for func
because it already found one in the derived class. The using
statement brings the other overload into the same scope so that it can participate in overload resolution.
這篇關(guān)于c++ 繼承類中函數(shù)重載的問題的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!