C++:派生类和虚方法
我想知道,在以下情况下记录的行为是什么:
您有
class A
{
virtual void A()
{
cout << "Virtual A"<<endl;
}
void test_A()
{
A();
}
}
class B: public A
{
void A()
{
cout << "Non-virtual A in derived class"<<endl;
}
void test_B()
{
A();
}
}
A a; B b;
a.test_A();
b.test_A();
b.test_B();
根据 C++ 标准它应该做什么,为什么? GCC 的工作方式类似于 B::A 也是虚拟的。
当您在派生类中用非虚拟方法覆盖虚拟方法时,通常会发生什么?
Possible Duplicates:
C++ : implications of making a method virtual
Why is 'virtual' optional for overridden methods in derived classes?
I wonder, what is documented behavior in the following case:
You have
class A
{
virtual void A()
{
cout << "Virtual A"<<endl;
}
void test_A()
{
A();
}
}
class B: public A
{
void A()
{
cout << "Non-virtual A in derived class"<<endl;
}
void test_B()
{
A();
}
}
A a; B b;
a.test_A();
b.test_A();
b.test_B();
What it supposed to do according to C++ standard and why?
GCC works like B::A is also also virtual.
What shoudl happen in general when you override virtual method by non-virtual one in derived class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果存在具有相同名称和签名的虚拟基类成员函数,则子类成员函数是隐式虚拟的。
The sub-class member function is implicitly virtual if a virtual base-class member function with the same name and signature exists.
该代码不应编译,因为您无法使用类的名称命名方法。但据我了解,这是你真正的问题:
答案是肯定的。一旦某个方法在类中被声明为虚拟方法,那么该方法的所有重写都将是虚拟的,并且 virtual 关键字在派生类中是可选的(即使我建议键入它,如果仅用于文档目的) 。请注意,对于要重写的派生类中的方法,它必须具有相同的名称和签名,唯一的潜在区别是协变返回类型:
The code should not compile as you cannot name a method with the name of the class. But regarding what I understand that is your real question:
The answer is yes. Once a method is declared virtual in a class, then all overrides of that method will be virtual, and the
virtual
keyword is optional in derived classes (even if I recommend typing it, if only for documentation purposes). Note that for a method in a derived class to be an override it has to have the same name and signature, with only potential difference being a covariant return type:这段代码格式不正确。构造函数不能有返回类型(就像您对“A”的构造函数所做的那样)。构造函数也不能是虚拟的。
修复 A 的构造函数后,类 B 的格式不正确,因为 A 的构造函数是私有的。
因此,这段代码存在很多问题(包括类定义中缺少分号)。
This code is ill-formed. A constructor cannot have a return type (as you have done for the constructor of 'A'). Also a constructor cannot be virtual.
After fixing A's constructor, class B is ill-formed as the constructor of A is private.
So, there are many problems with this code (including missing semicolons at the class definitions).
按照标准应该是
According to standard it should be