我有一个具有相同名称的函数,但在基类和派生类中具有不同的签名.当我尝试在继承自派生的另一个类中使用基类的函数时,我收到一个错误.请参阅以下代码:
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,一切正常.
这有什么问题?
鉴于以下示例,为什么我必须明确使用该语句b->A::DoSomething()而不仅仅是b->DoSomething()?
编译器的重载决议不应该弄清楚我在谈论哪种方法?
我正在使用Microsoft VS 2005.(注意:在这种情况下使用虚拟无效.)
class A
{
public:
int DoSomething() {return 0;};
};
class B : public A
{
public:
int DoSomething(int x) {return 1;};
};
int main()
{
B* b = new B();
b->A::DoSomething(); //Why this?
//b->DoSomething(); //Why not this? (Gives compiler error.)
delete b;
return 0;
}
Run Code Online (Sandbox Code Playgroud) 请考虑以下代码段:
struct Base
{
virtual ~Base() {}
virtual void Foo() const = 0; // Public
};
class Child : public Base
{
virtual void Foo() const {} // Private
};
int main()
{
Child child;
child.Foo(); // Won't work. Foo is private in this context.
static_cast<Base&> (child).Foo(); // Okay. Foo is public in this context.
}
Run Code Online (Sandbox Code Playgroud)
这是合法的C++吗?"这"正在改变派生类中的虚函数访问模式.