1.题目
2-1 Point类的定义
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
通过本题目的练习可以掌握类与对象的定义;
设计一个点类Point,它具有私有数据成员x(横坐标)、y(纵坐标);公有成员函数:SetPoint(int,int)用于设置点对象的值,ShowPoint()用于输出点对象的信息
在主函数中调用成员函数SetPoint(int,int)为点对象设置值,并调用成员函数ShowPoint()输出点的信息。
Input
无
Output
一对圆括号内,x和y的值用逗号间隔
Sample Input
无
Sample Output
(10,11)
2.正确代码
这里给出两套代码,一个是用构造函数,一个是用普通函数,这两点区别和用法应该注意好。
构造函数
#include <iostream>
using namespace std;
class Point
{
int x,y;
public:
Point(int a,int b):x(a),y(b){};
Point()=default;
void ShowPoint()
{
cout << '(' << x << ',' << y << ')' << endl;
}
};
int main()
{
Point a(10,11);
a.ShowPoint();
return 0;
}
普通函数
#include <iostream>
using namespace std;
class Point
{
int x,y;
public:
void SetPoint(int a,int b){x=a;y=b;}
void ShowPoint()
{
cout << '(' << x << ',' << y << ')' << endl;
}
};
int main()
{
Point a;
a.SetPoint(10,11);
a.ShowPoint();
return 0;
}
3.代码解析
这个算是很基础的了吧,就不需要太多解析了。但应该明确。
Point(int a,int b):x(a),y(b){};
这种特别的书写形式只能在构造函数中使用,不能在普通函数中使用。
本文介绍了一个简单的C++ Point类实现,包括构造函数和普通函数两种方式,演示如何设置和显示点坐标。
2112

被折叠的 条评论
为什么被折叠?



