头歌实训 虚函数与多态性 面向对象啊实验

因为拼单词错了找了半个小时bug

文章目录

坐标计算

摩托车类



坐标计算

测试说明

平台会对你编写的代码进行测试:

输入描述:空格隔开的两个整数x和y,表示一个坐标

输出描述:输出结果为5行,分别执行并输出p,p++,++p,p--,--p的结果

测试输入: 1 2

预期输出:
(1, 2)
(1, 2)
(3, 4)
(3, 4)
(1, 2)

#include <iostream>
using namespace std;

class Point
{
	int _x, _y;
public:
	Point(int x=0, int y=0) : _x(x), _y(y) {}
	Point& operator++();
	Point operator++(int);
	Point& operator--();
	Point operator--(int);
	friend ostream& operator << (ostream& o, const Point& p);
};

/********** Begin **********/
Point& Point::operator++() {
	_x++;
	_y++;
	return *this;
}
Point Point::operator++(int) {
	Point old = *this;
	++(*this);
	return old;
}
Point& Point::operator--() {
	_x--;
	_y--;
	return *this;
}
Point Point::operator--(int) {
	Point old = *this;
	--(*this);
	return old;
}

/**********  End  **********/

ostream& operator << (ostream& o, const Point& p) {
	o << '(' << p._x << ", " << p._y << ')';
	return o;
}

int main()
{
	int x,y;
	cin>>x>>y;
	Point p(x, y);
	cout << p << endl;
	cout << p++ << endl;
	cout << ++p << endl;
	cout << p-- << endl;
	cout << --p << endl;
	return 0;
}

摩托车类

输出把基类中 Run、Stop 声明为虚函数时主程序的输出结果

平台会对你编写的代码进行测试:

测试输入:无
预期输出:
vehicle run!
vehicle stop!
bicycle run!
bicycle stop!
motocar run!
motocar stop!
motocycle run!
motocycle stop!
vehicle run!
vehicle stop!
bicycle run!
bicycle stop!
motocar run!
motocar stop!
motocycle run!
motocycle stop!

#include <iostream>
using namespace std;


/********** Begin **********/
class Vehicle {
public:
	virtual void Run() { cout << "vehicle run!" << endl; }
	virtual void Stop() { cout << "vehicle stop!" << endl; }

};
class Bicycle :virtual public Vehicle {
public:
	 void Run() { cout << "bicycle run!" << endl; }
	 void Stop() { cout << "bicycle stop!" << endl; }
};
class Motorcar :virtual public Vehicle {
public:
	virtual void Run() { cout << "motocar run!" << endl; }
	virtual void Stop() { cout << "motocar stop!" << endl; }
};

// class Motorcar :virtual public vehicle {
// public:
// 	virtual void run() { cout << "motorcar run!" << endl; }
// 	virtual void stop() { cout << "motorcar stop!" << endl; }
// };
/**********  End  **********/

class Motorcycle : public Bicycle, public Motorcar
{
public:
	void Run() {cout << "motocycle run!" << endl;}
	void Stop() {cout << "motocycle stop!" << endl;}
};

int main()
{
	Vehicle v;
	v.Run();
	v.Stop();
	Bicycle b;
	b.Run();
	b.Stop();
	Motorcar m;
	m.Run();
	m.Stop();
	Motorcycle mc;
	mc.Run();
	mc.Stop();
	Vehicle* vp = &v;
	vp->Run();
	vp->Stop();
	vp = &b;
	vp->Run();
	vp->Stop();
	vp = &m;
	vp->Run();
	vp->Stop();
	vp = &mc;
	vp->Run();
	vp->Stop();
	return 0;
}

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值