- 关 键 词:
- visual basic
- 数据存储
- c++
但是在实际工作中,很可能会碰到对象所属类不清的情况,下面我们来看一下派生类成员作为函数参数传递的例子,代码如下:
//例程2
#include <iostream>
using namespace std;
class Vehicle
{
public:
Vehicle(float speed,int total)
{
Vehicle::speed=speed;
Vehicle::total=total;
}
void ShowMember()
{
cout<<speed<<"|"<<total<<endl;
}
protected:
float speed;
int total;
};
class Car:public Vehicle
{
public:
Car(int aird,float speed,int total):Vehicle(speed,total)
{
Car::aird=aird;
}
void ShowMember()
{
cout<<speed<<"|"<<total<<"|"<<aird<<endl;
}
protected:
int aird;
};
void test(Vehicle &temp)
{
temp.ShowMember();
}
void main()
{
Vehicle a(120,4);
Car b(180,110,4);
test(a);
test(b);
cin.get();
}
例子中,对象a与b分辨是基类和派生类的对象,而函数test的形参却只是Vehicle类的引用,按照类继承的特点,系统把Car类对象看做是一个Vehicle类对象,因为Car类的覆盖范围包含Vehicle类,所以test函数的定义并没有错误,我们想利用test函数达到的目的是,传递不同类对象的引用,分别调用不同类的,重载了的,ShowMember成员函数,但是程序的运行结果却出乎人们的意料,系统分不清楚传递过来的基类对象还是派生类对象,无论是基类对象还是派生类对象调用的都是基类的ShowMember成员函数。
文章地址: http://www.qqread.com/cpp/p320689030.html
更多内容请看C/C++技术专题专题,或进入讨论组讨论。
相关专题
- C/C++技术专题 (1637篇文章)
- Java语言和C++语言的差异 (29次浏览)
- 在C++中实现四种进程或线程同步互斥的控制 (0次浏览)
- Ubuntu下面的C语言代码检查工具 Splint (0次浏览)



