C++简单举例:类外实现一个完整的类

--前言:哎,人有点蠢。才开始学C++,作为新新手写代码当然报了一大堆的错。不停的百度过后就有了这篇文章。在这期间看到一个博客主自己搭建的属于自己的博客网站。我准备好好学习,争取自己也搭一个。


1.实现要求:

        就是输入坐标,然后将坐标加起来的故事(只是在类外实现而已)。

   被强制性要求这样写:

   Point(int xx = 0, int yy =0);

   int getX() const;

   int getY() const;

   void setX(int xx);

   void setY(int yy);

2.一言不合放代码

#include <iostream>
using namespace std;
class point//声明一个point类
{
//声明相关的成员方法
public:
point(int xx = 0, int yy = 0);
int getX() const;//   若将成员成员函数声明为const,则该函数不允许修改类的数据成员
int getY() const;
void setX(int xx);
void setY(int yy);
friend ostream &operator<<(ostream &os, const point &p);//友元函数
friend point operator+(const point a, const point b);
//声明相关的成员变量
private:
int x;
int y;
};
//实现所有成员方法,先写该方法返回类型,再写该成员方法属于的类,类名之后要加::,再写方法名和参数及实现
// 在C++中,只有被声明为const的成员函数才能被一个const类对象调用。
void point::setX(int xx)
{
x = xx;
}
void point::setY(int yy)
{
y = yy;
}
int point::getX ()const
{
return x;
}
int point::getY ()const//在类体之外定义const成员函数时,还必须加上const关键字
{
return y;
}
 point::point(int xx,int yy)//构造函数的作用:初始化对象的数据成员。
{
setX(xx);
setY(yy);
}
 point operator+(const point z, const point zz)
 {
point h;
h.x = z.x + zz.x;
h.y = z.y + zz.y;
return h;
 }
 ostream &operator<<(ostream &os, const point &p)
 {
os << "[" << p.x << "," << p.y << "]";
return os;
 }
 void printpoint(const point & p)
 {
cout << "[" << p.getX() << "," << p.getY() << "]";
return;
 }

//main方法入口
int main()
{
point a;
printpoint(a);
cout << endl;
point b(2);
printpoint(b);
cout << endl;
int x0;
int y0;
cin >> x0;
cin >> y0;
point c(x0,y0);
printpoint(c);
cout << endl;
printpoint(b);
cout << "+";
printpoint(c);
cout << "=";
a = b + c;
printpoint(a);
cout << endl;
system("pause");//避免VS运行闪退
return 0;
}
//const的使用注意事项:
/*const成员函数可以访问非const对象的非const数据成员、const数据成员,也可以访问const对象内的所有数据成员;
  非const成员函数可以访问非const对象的非const数据成员、const数据成员,但不可以访问const对象的任意数据成员;
*/




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值