引入派生类后的对象指针

// 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值