c++ 面向对象基础Test——继承、重载、slice赋值

本文通过C++代码实例详细解释了类的构造、析构、虚方法、方法覆盖和方法重载的概念。通过创建一个基类`Person`和一个派生类`Fan`,展示了如何在派生类中调用基类方法,并实现了方法的重载和覆盖。此外,介绍了使用指针和引用操作不同类型的对象。最后,演示了析构函数的调用和内存释放过程。

n

// CppTest1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <string>
#include <iostream>

#define PTLN(str) std::cout << "[" << str << "]" << "-------------------" << std::endl;
#define PT(str) std::cout << str << std::endl;

class Person
{
public:

	// 构造函数
	Person()
	{
		PT("Person()");
	}

	// 析构函数
	virtual ~Person()
	{
		PT("~Person()");
	}

	// 定义虚方法
	virtual void fun()
	{
		PT("Person::fun()");
	}

	// 定义方法
	void fun0()
	{
		PT("Person::fun0()");
	}


};

class Fan : public Person
{
public:

	// 构造函数
	Fan()
	{
		PT("Fan()");
	}

	// 析构函数
	virtual ~Fan()
	{
		PT("~Fan()");
	}

	// 方法重载
	virtual void fun() override
	{
		PT("Fan::fun()");
	}

	// 方法覆盖
	void fun0()
	{
		PT("Fan::fun0()");
	}

};

int _tmain(int argc, _TCHAR* argv[])
{
	
	Fan* f1 = new Fan();

	PTLN(0)

	f1->fun0();

	f1->fun();

	PTLN(1) //------------------

	Person* p1 = f1;

	p1->fun0();

	p1->fun();

	PTLN(2) //------------------

	Person p2 = *f1;

	(&p2)->fun0();

	(&p2)->fun();

	PTLN(3) //------------------

	delete f1;

	system("pause");

	return 0;
}

运行结果:

Person()
Fan()
[0]-------------------
Fan::fun0()
Fan::fun()
[1]-------------------
Person::fun0()
Fan::fun()
[2]-------------------
Person::fun0()
Person::fun()
[3]-------------------
~Person()
~Fan()
~Person()
请按任意键继续. . .



n

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值