// ObjectPointer.cpp : Defines the entry point for the console application.
#include "stdafx.h"
//#include <iostream.h> vc6中写法
#include <iostream> // vs2005中去掉.h,若用到cout,cin需 using namespace std
using namespace std;
#include <string.h>
#include <conio.h>
class bstring //基类
{
char *name;
int length;
public:
bstring(char *str)
{
length=strlen(str);
name=new char[length+1];
strcpy(name,str);
}
void show()
{
cout<<name<<"/n";
}
};
class de_string:public bstring //派生类
{
int age;
public:
de_string(char *str,int age):bstring(str)//基类带参数的构造函数
{
de_string::age=age;
}
void show()
{
bstring::show();
cout<<"the age is"<<age<<endl;
}
void showage()
{
cout<<"single the age is"<<age<<endl;
}
};
int main(int argc, char* argv[])
{
bstring s1("smith"),*pstr1;
de_string s2("sean",20),*pstr2;
pstr1=&s1;
pstr1->show();
pstr1=&s2;//1.可以用一个声明为指向基类对象的指针指向它的公有派生类对象,若为私有派生,则被禁止.
pstr1->show();//虽然指向派生类对象,但仍调用基类的show
pstr2=&s2; //de_string型指针pstr2,调用派生类show
pstr2->show();
//pstr2=&s1; //2.错误:不能将一个声明为指向派生类对象的指针指向其基类的一个对象
//pstr2->show();
//pstr1->showage();
//3.错误:声明为指向基类对象的指针,当其指向派生类对象时,只能利用它来直接访问派生类中从其类继承来的
//成员,不能直接访问公有派生类中特定的成员.
((de_string *)pstr1)->showage();//正确
char c=_getch();
return 0;
}