美文网首页
C++学习第10课,类内运算符重载

C++学习第10课,类内运算符重载

作者: Mr小熊_1da7 | 来源:发表于2019-06-16 17:59 被阅读0次

1 先上代码


#include <iostream>

#include <string.h>

#include <unistd.h>

using namespace std;

class Point {

private:

int x;

int y;

public:

Point()

{

cout<<"Point()"<<endl;

}

Point(int x, int y) : x(x), y(y)

{

cout<<"Point(x,y)"<<endl;

}

Point(const Point &per)

{

cout<<"Point(copy)"<<endl;

x = per.x;

y = per.y;

}

~Point()

{

cout<<"~Point()"<<endl;

}

int getX(){ return x; }

int getY(){ return y; }

void setX(int x){ this->x = x; }

void setY(int y){ this->y = y; }

void printInfo()

{

cout<<"("<<x<<", "<<y<<")"<<endl;

}

/*+加法*/

Point operator+(Point &a)

{

Point n;

n.x = this->x+a.x;

n.y = this->y+a.y;

cout<<"operator+(Point &a)"<<endl;

return n;

}

Point operator++(int b)

{

Point n;

n.x = this->x++;

n.y = this->y++;

cout<<"p++"<<endl;

return n;

}

Point& operator++(void)

{

this->x++;

this->y++;

cout<<"++p"<<endl;

return *this;

}

friend ostream& operator<<(ostream& cout, Point &a);

};

/*这里是<<*/

ostream& operator<<(ostream& cout, Point &a)

{

cout<<"("<<a.x<<", "<<a.y<<")";

return cout;

}

int main(int argc, char **argv)

{

cout<<"*******************"<<endl;

Point p1(1, 2);

Point p2(2, 3);

cout<<"*******************"<<endl;

Point m1 = p1+p2;

Point m2 = p1++;

Point m3 = ++p1;

cout<<"*******************"<<endl;

cout <<"Port = "<<p1<<endl;

return 0;

}



自己看

相关文章

  • 13. C++基本运算符重载

    基本上我们进行运算符重载时有两种形式,类内的运算符重载和顶层函数位置的运算符重载。 操作符重载指的是将C++提供的...

  • 1.2.21_C++ 类成员访问运算符 -> 重载

    C++ 重载运算符和重载函数 类成员访问运算符( -> )可以被重载,但它较为麻烦。它被定义用于为一个类赋予"指针...

  • C++类的运算符重载

    C++类运算符重载是一种方便的语法,例如可以执行两个类相加 类的运算符重载语法如下

  • 运算符重载与友元函数

    运算符重载 C++允许将运算符重载到用户定义的类型,例如,使用+将两个类对象相加。 重载运算符要使用运算符函数: ...

  • 1.2.19_C++ 函数调用运算符 () 重载

    C++ 重载运算符和重载函数 函数调用运算符 () 可以被重载用于类的对象。当重载 () 时,您不是创造了一种新的...

  • 第十一章 使用类

    运算符重载 运算符重载是一种形式的C++多态。运算符重载将重载的概念扩展到运算符上,允许赋予C++运算符多种含义。...

  • 1.2.15_C++ 关系运算符重载

    C++ 重载运算符和重载函数 C++ 语言支持各种关系运算符( < 、 > 、 <= 、 >= 、 == 等等),...

  • C++面向对象继承与操作符重载

    1.类外运算符重载。 2.类里运算符重载。 3.括号运算符。 4.C++对象继承。 C++多继承 会出现二义性 处...

  • C++ 运算符重载

    运算符重载将重载的概念扩展到运算符上,允许赋予C++运算符多种含义。实际上,很多C++运算符已经重载。将*运算符用...

  • C++运算符重载

    C++运算符重载的实质:运算符重载的实质就是函数重载或函数多态。运算符重载是一种形式的C++多态。目的在于让人能够...

网友评论

      本文标题:C++学习第10课,类内运算符重载

      本文链接:https://www.haomeiwen.com/subject/jurxfctx.html