考虑一下代码:
#include <stdio.h>
class Base {
public:
virtual void gogo(int a){
printf(" Base :: gogo (int) \n");
};
virtual void gogo(int* a){
printf(" Base :: gogo (int*) \n");
};
};
class Derived : public Base{
public:
virtual void gogo(int* a){
printf(" Derived :: gogo (int*) \n");
};
};
int main(){
Derived obj;
obj.gogo(7);
}
Run Code Online (Sandbox Code Playgroud)
得到此错误:
>g++ -pedantic -Os test.cpp -o test test.cpp: In function `int main()': test.cpp:31: error: no matching function for call to `Derived::gogo(int)' test.cpp:21: note: candidates are: virtual …
我写下面的代码是为了解释我的问题.如果我注释第11行(使用关键字"using"),编译器不会编译该文件并显示以下错误:invalid conversion from 'char' to 'const char*'.它似乎没有void action(char)在Parent类中看到Son类的方法.
为什么编译器会以这种方式运行?或者我做错了什么?
class Parent
{
public:
virtual void action( const char how ){ this->action( &how ); }
virtual void action( const char * how ) = 0;
};
class Son : public Parent
{
public:
using Parent::action; // Why should i write this line?
void action( const char * how ){ printf( "Action: %c\n", *how ); }
};
int main( int argc, char** argv ) …Run Code Online (Sandbox Code Playgroud) 这可能是一个noob问题,抱歉.我最近遇到了一个奇怪的问题,试图在c ++,函数重载和继承中搞乱一些高级的东西.
我将展示一个简单的例子,只是为了证明这个问题;
有两个班,classA和classB如下;
class classA{
public:
void func(char[]){};
};
class classB:public classA{
public:
void func(int){};
};
Run Code Online (Sandbox Code Playgroud)
据我所知classB,现在应该拥有两个func(..)函数,由于参数不同而重载.
但是在主方法中尝试这个时;
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;
}
Run Code Online (Sandbox Code Playgroud)
它给出了错误,因为void func(char[]){}; 超类中的方法classA在派生类中是不可见的classB.
我怎么能克服这个?这不是在c ++中如何重载?我是c ++的新手,但在Java中,我知道我可以使用这样的东西.