c++实验4 多态和虚函数

本文深入探讨了C++中的面向对象编程概念,包括日期类的实现与比较、点和圆的面积计算、抽象基类的使用以及友元函数的应用。通过具体实例,展示了继承、多态、虚函数和友元等核心特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
using namespace std;

class Date
{
public:
	Date(int y = 0, int m = 0, int d = 0)
	{
		year = y;
		month = m;
		day = d;
	};
	void operator=(Date &date);
	void output() { cout << year << "," << month << "," << day << endl; }
	friend bool operator>(Date d1, Date d2);
private:
	int year, month, day;
};


void Date:: operator=(Date &date)
{
	year = date.year;
	month = date.month;
	day = date.day;
}
bool operator>(Date d1, Date d2)
{
	bool flag = false;
	if (d1.year > d2.year)flag = true;
	else if (d1.year == d2.year)
		if (d1.month > d2.month)flag = true;
		else if (d1.month == d2.month)
			if (d1.day > d2.day)flag = true;
	return flag;
}
void main()
{
	Date date1(2017, 4, 27);
	Date date2(2018, 4, 27), date3;
	date3 = date1;
	cout << "date3:";
	date3.output();
	cout << "date2>date3 is";
	cout << boolalpha << (date2 > date3);
}
#include<iostream>
using namespace std;
class Point
{
public:
	Point(double m, double n) { x = m; y = n; }
	virtual void Area() { cout << "The area is 0" << endl; }
private:
	double x, y;
};
class Circle :public Point
{
public:
	Circle(double m, double n, double i) :Point(m, n) { r = i; }
	void Circle::Area()
	{
		double a = 3.14*r*r;
		cout << "The area of the circle is:" << a << endl;
	}
private:
	double r;
};
void main()
{
	Point *pt;
	Circle c(4, 5, 6);
	pt = &c;
	pt->Area();
}
#include<iostream>
using namespace std;
class Add
{
public:
	virtual void sm() = 0;
	virtual void disp(){}
};
class DAdd:public Add
{
public:
	DAdd(int a, int b) { m1 = a; n1 = b; }
	void sm() { m1 += n1; n1--; }
	void disp() { cout << "m1=" << m1 << "  " << "n1=" << n1 << endl; }
private:
	int m1, n1;;
};
void main()
{
	DAdd a(4, 6);
	Add *p = &a;
	p->sm();
	p->disp();
}
#include<iostream>
using namespace std;
class Animal
{
protected:
	int age;
	friend void print_age(Animal &a);
};
class Dog:public Animal
{
public:
	Dog() { this->age = 2; }
	~Dog() {};
};
class Cat :public Animal
{
public:
	Cat() { this->age = 1; }
	~Cat(){}
};
void print_age(Animal &a)
{
	cout << "my age= " << a.age << endl;
}
void main()
{
	Cat kitty;
	Dog jd;
	print_age(kitty);
	print_age(jd);
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值