我有一个具有相同名称的函数,但在基类和派生类中具有不同的签名.当我尝试在继承自派生的另一个类中使用基类的函数时,我收到一个错误.请参阅以下代码:
class A
{
public:
void foo(string s){};
};
class B : public A
{
public:
int foo(int i){};
};
class C : public B
{
public:
void bar()
{
string s;
foo(s);
}
};
Run Code Online (Sandbox Code Playgroud)
我从gcc编译器收到以下错误:
In member function `void C::bar()': no matching function for call to `C::foo(std::string&)' candidates are: int B::foo(int)
Run Code Online (Sandbox Code Playgroud)
如果我int foo(int i){};从课堂上删除B,或者我将其重命名foo1,一切正常.
这有什么问题?
我写下面的代码是为了解释我的问题.如果我注释第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) 这不起作用:
class Foo
{
public:
virtual int A(int);
virtual int A(int,int);
};
class Bar : public Foo
{
public:
virtual int A(int);
};
Bar b;
int main()
{
b.A(0,0);
}
Run Code Online (Sandbox Code Playgroud)
看来,通过重写Foo::A(int)与Bar::A(int)我莫名其妙地隐藏Foo::A(int,int).如果我添加一些Bar::A(int,int)东西工作.
有没有人能够很好地描述这里发生的事情?
我不知道为什么我得到一个"错误C2660:'SubClass :: Data':函数不带2个参数".当我尝试编译我的项目时.
我有一个基类,其中包含一个名为data的函数.该函数接受一个参数,数据重载需要2个参数.在我的subClass中,我覆盖了带有1个参数的数据函数.现在,当我尝试从指向subClass的指针调用数据的重载时,我收到上面的编译错误.
class Base : public CDocument
{
Public:
virtual CString& Data( UINT index);
CString Data( UINT index, int pos);
};
class SubClass : public Base
{
Public:
virtual CString& Data( UINT index);
};
Void SomeOtherFunction()
{
subType* test = new subType();
test->Data( 1, 1);// will not compile
((Base*)test)->Data(1,1); // compiles with fine.
}
Run Code Online (Sandbox Code Playgroud) c++ ×4
inheritance ×2
c++-faq ×1
function ×1
lookup ×1
oop ×1
overloading ×1
overriding ×1
using ×1
visual-c++ ×1