c++ virtual

1. 了解虚函数

虚函数是应该在派生类中重新定义的成员函数,即便是基类中的成员函数调用虚函数,也会调用到派生类中的版本。虚函数也是实现C++多态特性的一部分。

2. 实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# include <iostream>
# include <vector>
using namespace std;
class Animal
{
public:
virtual void eat() const { cout << "I eat like a generic Animal." << endl; }
virtual ~Animal() {}
};
class Wolf : public Animal
{
public:
void eat() const { cout << "I eat like a wolf!" << endl; }
};
class Fish : public Animal
{
public:
void eat() const { cout << "I eat like a fish!" << endl; }
};
class GoldFish : public Fish
{
public:
void eat() const { cout << "I eat like a goldfish!" << endl; }
};
class OtherAnimal : public Animal
{
};
int main()
{
std::vector<Animal*> animals;
animals.push_back( new Animal() );
animals.push_back( new Wolf() );
animals.push_back( new Fish() );
animals.push_back( new GoldFish() );
animals.push_back( new OtherAnimal() );
for(auto it = animals.begin(); it != animals.end(); ++it) {
(*it)->eat();
delete *it;
}
return 0;
}
#include <iostream>
using namespace std;
class Account {
public:
Account( double d ) {
_balance = d;
}
virtual double GetBalance() {
return _balance;
}
virtual void PrintBalance() {
cerr << "Error. Balance not available for base type." << endl;
}
private:
double _balance;
};
class CheckingAccount : public Account {
public:
CheckingAccount(double d) : Account(d) {}
void PrintBalance() {
cout << "Checking account balance: " << GetBalance() << endl;
}
};
class SavingsAccount : public Account {
public:
SavingsAccount(double d) : Account(d) {}
void PrintBalance() {
cout << "Savings account balance: " << GetBalance() << endl;
}
};
int main() {
CheckingAccount *pChecking = new CheckingAccount( 100.00 ) ;
SavingsAccount *pSavings = new SavingsAccount( 1000.00 );
Account *pAccount = pChecking;
pAccount->PrintBalance();
pAccount = pSavings;
pAccount->PrintBalance();
}