2010-11-12 115 views
1

可能重复:
C++ : implications of making a method virtual
Why is 'virtual' optional for overridden methods in derived classes?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一样也是虚拟的。

当你在派生类中通过非虚拟方法覆盖虚拟方法时,通常会发生什么?

+6

您的代码[不应编译](HTTP: //ideone.com/gI9bI)。 – 2010-11-12 11:16:11

+0

我认为这也是答案在这里:http://stackoverflow.com/questions/2963965/why-is-virtual-optional-for-overridden-methods-in-derived-classes – mkj 2010-11-12 11:18:10

回答

3

如果存在具有相同名称和签名的虚拟基类成员函数,则子类成员函数是隐式虚拟的。

+0

@Downvoter:请解释一下,我想学习。 – 2010-11-12 11:18:18

+0

您需要更仔细地查看代码。顺便说一句,我没有downlvoted。 – 2010-11-12 11:19:37

+1

代码不起作用,我看到了,但我回答了最后一行中提出的问题。就此而言,我的回答是正确的。 – 2010-11-12 11:21:17

0

根据标准它应该是

 
A a; B b; 
a.test_A(); //"Virtual A" 
b.test_A(); //Non-virtual A in derived class 
b.test_B(); //Non-virtual A in derived class 
0

是形成不良的这种代码。构造函数不能有返回类型(就像你为'A'的构造函数所做的那样)。另外一个构造函数不能是虚拟的。

修复了A的构造函数之后,B类是格式不正确的,因为A的构造函数是私有的。

所以,这个代码有很多问题(包括在类定义中缺少分号)。

2

代码不应该编译,因为您不能使用类的名称命名方法。但是对于我个人理解这是你真正的问题:

将使得虚拟的方法意味着,在所有派生类同样的方法是虚拟的,即使virtual关键词不存在?

答案是肯定的。一旦某个方法在类中被声明为虚拟的,那么该方法的所有重写将是虚拟的,并且关键字在派生类中是可选的(即使我建议仅为了文档目的而键入它)。请注意,对于一个方法在派生类是它必须具有相同的名称和签名的覆盖,只有电位差是一个协变返回类型:

struct A {}; 
struct B : A {}; 
struct base { 
    virtual A* foo(); 
    virtual A* bar(); 
}; 
struct derived : base { 
    virtual B* foo(); // override, covariant return type 
    virtual int bar(); // not override, return type is not covariant 
    virtual A* bar(int); // not override, different argument list 
}; 
+0

是的:我想是的。问题的最后部分正是如此。 +1 – Chubsdad 2010-11-12 11:33:29