1.1
#include <iostream>
using namespace std;
class Vehicle
{
public:
void run() const { cout << "run a vehicle. "<<endl; } //(2) run()为虚函数
};
class Car: public Vehicle
{
public:
void run() const {cout << "run a car. "<<endl; }
};
class Airplane: public Vehicle
{
public:
void run() const {cout << "run a airplane. "<<endl;}
};
int main()
{
cout<<"(a) 直接用对象访问成员函数: "<<endl;
Vehicle v;
v.run();
Car car;
Airplane airplane;
car.run();
airplane.run();
cout<<"(b) 用指向基类的指针访问成员函数: "<<endl;
Vehicle *vp;
vp=&car;
vp->run();
vp=&airplane;
vp->run();
system("pause");
return 0;
}
(a) 直接用对象访问成员函数:
run a vehicle.
run a car.
run a airplane.
(b) 用指向基类的指针访问成员函数:
run a vehicle.
run a vehicle.
请按任意键继续. . .
1.2
#include <iostream>
using namespace std;
class Vehicle
{public:
virtual void run() const { cout << "run a vehicle. "<<endl; } //(2) run()为虚函数
};
class Car: public Vehicle
{
public:
void run() const {cout << "run a car. "<<endl; }
};
class Airplane: public Vehicle
{
public:
void run() const {cout << "run a airplane. "<<endl;}
};
int main()
{
cout<<"(a) 直接用对象访问成员函数: "<<endl;
Vehicle v;
v.run();
Car car;
Airplane airplane;
car.run();
airplane.run();
cout<<"(b) 用指向基类的指针访问成员函数: "<<endl;
Vehicle *vp;
vp=&car;
vp->run();
vp=&airplane;
vp->run();
system("pause");
return 0;
}
(a) 直接用对象访问成员函数:
run a vehicle.
run a car.
run a airplane.
(b) 用指向基类的指针访问成员函数:
run a car.
run a airplane.
请按任意键继续. . .
1.3
#include <iostream>
using namespace std;
class Vehicle
{public:
virtual void run() const = 0; //(3) run()为纯虚函数
};
class Car: public Vehicle
{
public:
void run() const {cout << "run a car. "<<endl; }
};
class Airplane: public Vehicle
{
public:
void run() const {cout << "run a airplane. "<<endl;}
};
int main()
{
cout<<"(a) 直接用对象访问成员函数: "<<endl;
Car car;
Airplane airplane;
car.run();
airplane.run();
cout<<"(b) 用指向基类的指针访问成员函数: "<<endl;
Vehicle *vp;
vp=&car;
vp->run();
vp=&airplane;
vp->run();
system("pause");
return 0;
(a) 直接用对象访问成员函数:
run a car.
run a airplane.
(b) 用指向基类的指针访问成员函数:
run a car.
run a airplane.
请按任意键继续. . .