在询问之前,我提到了这个older question。但我仍有疑问。
struct B1 {
virtual void fun () = 0;
};
struct B2 {
void fun () { cout<<"B2::fun()\n"; }
void fun (int i) {}
};
struct D : B1, B2 {
using B2::fun; // This line doesn't help
};
int main ()
{
B1 *pB1 = new D; // Error: cannot allocate 'D' because 'B1::fun()' is abstract
pB1->fun();
}
pure virtual
机制?using
关键字不能帮助解决这个错误?(编译器: linux-64 g++)using
关键字、B2::fun()
还是B2::fun(int)
?(这一行没有歧义)发布于 2011-04-11 06:00:43
哪个函数用于使用关键字: B2::fun()还是B2::fun(int)?))没有歧义。
(这一行)
14882:2003(E) 7.3.3.12
当使用声明将基类的名称引入派生类范围时,派生类中的成员函数覆盖和/或隐藏基类中具有相同名称和参数类型的成员函数(而不是相互冲突)。
[Example:
struct B {
virtual void f(int);
virtual void f(char);
void g(int);
void h(int);
};
struct D : B {
using B::f;
void f(int); // OK: D::f(int) overrides B::f(int);
using B::g;
void g(char); // OK
using B::h;
void h(int); // OK: D::h(int) hides B::h(int)
};
void k(D* p) {
p->f(1); //calls D::f(int)
p->f(’a’); //calls B::f(char) // Notice the call being resolved
p->g(1); //calls B::g(int)
p->g(’a’); //calls D::g(char)
}
— end example]
注意:两个使用-声明可能引入具有相同名称和相同参数类型的函数。如果对不限定函数名的调用,函数重载解析选择由此类使用-声明引入的函数,则函数调用的格式不正确。
因此,在您提供的示例中,根本不存在任何歧义。根据传递的参数,可以决定对方法的调用。
发布于 2011-04-11 05:34:56
好的。不过,我还是根据逻辑推理得到了第一个答案。假设标准接受继承的方法来解决pure virtual
机制,那么正常的“虚拟”函数就会出现模糊。
假设B1::fun()
是正常的虚函数,那么在B1::fun()
和B2::fun()
之间就会有一种选择混淆。所以最好避免考虑继承的成员,至少对于virtual
机制是这样。
发布于 2011-04-11 05:42:57
using
只调整名称查找过程。它不将函数导入给定的作用域,也不定义新函数。
因此,您只需定义一个新的virtual
覆盖。
https://stackoverflow.com/questions/5617043
复制相似问题