热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

在继承过程中遇到的困惑与挑战(依然感到迷茫)

#includeusingnamespacestd;classFather{public:Father(){coutffcf;coutfc;coutcf;coutf;

#include
using namespace std;
class Father
{
public:
Father()
{
cout <<"i am father \n";
}
virtual void print()
{
cout <<" 我是父类的:";
cout <f <}
public:
int f;
};
class Child :public Father
{
public:
Child()
{
cout <<"i am child \n";
}
virtual void print()
{
cout <<" 我是子类的: ";
cout <f <cout <c <}
public:
int c;
};
void objplay(Father *tem1)
{
cout <<"形参为 Father *tem1 的 tem1->f==========>";
cout <f <}
void objplay2(Child *tem2)
{
cout <<"形参为 Child *tem2 的 tem2->c==========>";
cout <c <cout <<"形参为 Child *tem2 的 tem2->f==========>";
cout <f <}
int main()
{
Child c1;
Father f1;
c1.c = 5;
c1.f = 6;
cout <<"c1.print()=====> ";
c1.print();//调用子类的 输出为6
f1.f = 7;
cout <<"f1.print()=====> ";
f1.print();//调用父类的 输出为7
//Child *c2; 这样子写就会出错,因为指针使用的时候必须必须分配内存空间
Child *c2 = new Child;//一旦用类名字定义函数就会调用析构函数。
//Father *f2;
Father *f2 = new Father;
c2->c = 8;
c2->f = 9;
cout <<"c2.print()=====> ";
c2->print();//调用子类的
f2->f = 10;
cout <<"f2.print()=====> ";
f2->print();//调用父类的
objplay(&c1);// 这里虽然是父类的指针,但是指向的是子类的对象地址。所以调用显示的是子类的
objplay(&f1);//父类
objplay(c2);//这里居然也是调用的子类的值
objplay(f2);//父类
objplay2(&c1);
//objplay2(&f1); 出错
objplay2(c2);
//objplay2(f2); 出错
system("pause");
}

  

 

#include
#include
class A
{
public:
void FuncA()
{
printf("FuncA called\n");
}
virtual void FuncB()
{
printf("FuncB called\n");
}
};
class B : public A
{
public:
void FuncA()
{
A::FuncA();
printf("FuncAB called\n");
}
virtual void FuncB()
{
printf("FuncBB called\n");
}
};
void main(void)
{
B b;
A *pa;
pa = &b;
A *pa2 = new A;
pa->FuncA(); //这里的pa已经成为指向子类的指针了,所以调用的函数AB在用VIrtual的情形下,调用B的
pa->FuncB();// ( 4)
pa2->FuncA(); //( 5)
pa2->FuncB();
delete pa2;
system("pause");
}

  技术分享

 


推荐阅读
author-avatar
OkzYa-_916
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有