首页 > 其他 > 详细

继承中指向的迷茫(仍旧犯迷糊)

时间:2017-04-14 17:03:49      阅读:181      评论:0      收藏:0      [点我收藏+]
#include<iostream>
using namespace std;
class Father
{
public:
Father()
{
cout << "i am father \n";
}
virtual void print()
{
cout << " 我是父类的:";
cout << this->f << endl;
}
public:
int f;
};

class Child :public Father
{
public:
Child()
{
cout << "i am child \n";
}
virtual void print()
{
cout << " 我是子类的: ";
cout << this->f << endl;
cout << this->c << endl;
}
public:
int c;
};
void objplay(Father *tem1)
{
cout << "形参为 Father *tem1 的 tem1->f==========>";
cout << tem1->f << endl;
}

void objplay2(Child *tem2)
{
cout << "形参为 Child *tem2 的 tem2->c==========>";
cout << tem2->c << endl;
cout << "形参为 Child *tem2 的 tem2->f==========>";
cout << tem2->f << endl;
}
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<stdio.h>
#include<stdlib.h>
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");
}

  技术分享

 

继承中指向的迷茫(仍旧犯迷糊)

原文:http://www.cnblogs.com/xiaochige/p/6709710.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!