我有一个具有相同名称的函数,但在基类和派生类中具有不同的签名.当我尝试在继承自派生的另一个类中使用基类的函数时,我收到一个错误.请参阅以下代码:
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) 可能重复:
C++重载决议
我遇到了一个问题,在我的类重写了它的基类的函数后,所有重载的函数版本都被隐藏了.这是设计还是我做错了什么?
防爆.
class foo
{
public:
foo(void);
~foo(void);
virtual void a(int);
virtual void a(double);
};
class bar : public foo
{
public:
bar(void);
~bar(void);
void a(int);
};
Run Code Online (Sandbox Code Playgroud)
然后,下面会给出一个编译错误,说明条中没有(双)函数.
main()
{
double i = 0.0;
bar b;
b.a(i);
}
Run Code Online (Sandbox Code Playgroud) 在此示例中,类Foo和Bar从库中提供。我的课Baz从两者继承。
struct Foo
{
void do_stuff (int, int);
};
struct Bar
{
virtual void do_stuff (float) = 0;
};
struct Baz : public Foo, public Bar
{
void func ()
{
do_stuff (1.1f); // ERROR HERE
}
};
struct BazImpl : public Baz
{
void do_stuff (float) override {};
};
int main ()
{
BazImpl () .func ();
}
Run Code Online (Sandbox Code Playgroud)
我收到了编译错误reference to ‘do_stuff’ is ambiguous,这对我来说似乎是虚假的,因为两个函数签名完全不同。如果do_stuff是非虚拟的,我可以打电话Bar::do_stuff给它消除歧义,但是这样做会破坏多态性并导致链接器错误。
我可以func在do_stuff …
c++ virtual-functions multiple-inheritance overload-resolution name-lookup
这不起作用:
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)东西工作.
有没有人能够很好地描述这里发生的事情?
为什么编译器找不到基类函数签名?更改foo( a1 )到B::foo( a1 )的作品.
码:
class A1 ;
class A2 ;
class B
{
public:
void foo( A1* a1 ) { a1 = 0 ; }
} ;
class C : public B
{
public:
void foo( A2* /*a2*/ )
{
A1* a1 = 0 ;
foo( a1 ) ;
}
} ;
int main()
{
A2* a2 = 0 ;
C c ;
c.foo( a2 ) ;
return 0 ;
}
Run Code Online (Sandbox Code Playgroud)
编译器错误(VS2008):
error C2664: …Run Code Online (Sandbox Code Playgroud) c++ ×6
inheritance ×4
overriding ×2
c++-faq ×1
function ×1
lookup ×1
name-lookup ×1
oop ×1
overloading ×1
polymorphism ×1
using ×1