c++单目运算符

版权声明:chen_zan_yu https://blog.csdn.net/chen_zan_yu_/article/details/89363641

 操作符重载写在全局

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class Complex {
public:
	Complex(int a, int b) {
		this->a = a;
		this->b = b;
	}
	void printComplex() {
		cout << "(" << this->a << "," << this->b << ")" << endl;
	}
	friend Complex &operator++(Complex &c);

private:
	int a;
	int b;
};


//操作符重载写在全局
Complex &operator++(Complex &c) {
	c.a++;
	c.b++;
	return c;
}
int main() {

	Complex c1(1, 2);
	++c1;
	c1.printComplex();
	return 0;
}

 操作符重载写在局部

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class Complex {
public:
	Complex(int a, int b) {
		this->a = a;
		this->b = b;
	}
	void printComplex() {
		cout << "(" << this->a << "," << this->b << ")" << endl;
	}
	Complex &operator++() {
		this->a++;
		this->b++;
		return *this;
	 }

private:
	int a;
	int b;
};

int main() {

	Complex c1(1, 2);
	++++c1;
	c1.printComplex();
	return 0;
}

操作符重载的是后++运算符 全局

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class Complex {
public:
	Complex(int a, int b) {
		this->a = a;
		this->b = b;
	}
	void printComplex() {
		cout << "(" << this->a << "," << this->b << ")" << endl;
	}
	friend const Complex operator++(Complex &c1,int);

private:
	int a;
	int b;
};


//操作符重载的是后++运算符
const Complex operator++(Complex &c1,int) {
	Complex temp(c1.a, c1.b);
	c1.a++;
	c1.b++;
	return temp;
}
int main() {

	Complex c1(1, 2);
	c1++;
	c1.printComplex();
	return 0;
}

操作符重载的是后++运算符 局部 

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class Complex {
public:
	Complex(int a, int b) {
		this->a = a;
		this->b = b;
	}
	void printComplex() {
		cout << "(" << this->a << "," << this->b << ")" << endl;
	}
	const Complex operator++(int) {
		Complex temp(this->a, this->b);
		this->a++;
		this->b++;
		return temp;
	 }

private:
	int a;
	int b;
};

int main() {

	Complex c1(1, 2);
	c1++;
	c1.printComplex();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/chen_zan_yu_/article/details/89363641