1. 在继承的关系中,用作根类的类一般定义一个虚拟析构函数。
2. virtual
关键字的目的是实现动态绑定(dynamic binding), 成员函数默认非虚拟,对非虚拟函数的调用在编译时决定。
3. 除了构造函数,任何非静态成员函数都可以是虚拟的。
4. virtual
关键字只能用在类中的成员函数声明中,不能用在 class body 之外的函数定义中。派生类中如果要重定义子类中的虚函数,virtual
关键字可写可不写。基类中函数一旦声明为virtual
,则该函数永远为virtual
,子类中无法改变这点。
5. 在基类中,如果有任何函数需要子类重定义的,则定义为virtual
。
// Item sold at an undiscounted price
// derived classes will define various discount strategies
class Item_base {
public:
Item_base(const std::string &book = "", double sales_price = 0.0): isbn(book), price(sales_price) { }
std::string book() const { return isbn; }
// returns total sales price for a specified number of items
// derived classes will override and apply different discount algorithms
virtual double net_price(std::size_t n) const { return n * price; }
virtual ~Item_base() { }
private:
std::string isbn; // identifier for the item
protected:
double price; // normal, undiscounted price
};
void Bulk_item::memfcn(const Bulk_item &d, const Item_base &b)
{
// attempt to use protected member
double ret = price; // ok: uses this->price
ret = d.price; // ok: uses price from a Bulk_item object
ret = b.price; // error: no access to price from an Item_base
}
With one exception, the declaration (Section 7.4, p. 251)of a virtual function in the derived class must exactly match the way the function is defined in the base. That exception applies to virtuals that return a reference (or pointer) to a type that is itself a base class. A virtual function in a derived class can return a reference (or pointer) to a class that is publicly derived from the type returned by the base-class function.
一般情况下,派生类中的虚函数声明必须完全匹配基类中的声明,但有一个例外:如果基类的虚函数返回一个类one_class的引用(或指针),那么派生类的虚函数可以返回类one_class的公有派生的类的引用(或指针)。
我编的例子,这里的 Animal
和 Rabbit
可以分别替换成Base
和Derived
.
class Animal {};
class Rabbit : public Animal {};
class Base {
public:
virtual Animal& MyTest() {}
};
class Derived : public Base {
public:
Rabbit& MyTest() {} // Rabbit 可以换成 Animal
};
[1] 《 C++ primer 》15.2.1