C++友元函数学习笔记

2021/9/20 20:32:19

本文主要是介绍C++友元函数学习笔记,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 Complex &operator++() {

        real += 1;

        vir += 1;

        return *this;

}

其中&的作用是为了解决(++com)++的问题,com是Complex的一个对象,如果不加&那么++com返回值就不止com本身,之后的com++就不会在com的基础上++,最后cout << com;就只加了一个1,如果加了&就加了两个1

ostream &operator<<(ostream &out, const Complex &com) {}

其中&的作用是为了实现连续输出。


Complex &operator++(int);与Complex &operator++();的区别

第一个是处理++com的情况,第二个是处理com++的情况


想要返回值只能被访问不能被修改则在函数最前面加一个const

例:

const int operator[](...) const {}


以下是自己实现的一个复数类代码

#include<iostream>

using namespace std;

class Complex {
public:
	Complex(int real, int vir) : real(real), vir(vir) {
		cout << "Constructor : " << this << endl; 
	}
	Complex operator+(int val) {
		return Complex(real + val, vir + val);
	}
	Complex operator++(int val) {
		Complex ret(*this);
		real += 1;
		vir += 1;
		return ret;
	}
	Complex &operator++() {
		real += 1;
		vir += 1;
		return *this;
	}
	Complex operator--(int val) {
		Complex ret(*this);
		real -= 1;
		vir -= 1;
		return ret;
	}
	Complex &operator--() {
		real -= 1;
		vir -= 1;
		return *this;
	}
	Complex operator-(int val) {
		return Complex(real - val, vir - val);
	}
	Complex operator*(int val) {
		return Complex(real * val, vir * val);
	}
	Complex operator/(int val) {
		return Complex(real / val, vir / val);
	}
	friend Complex operator+(const Complex &, const Complex &);
	friend Complex operator*(const Complex &, const Complex &);
	friend Complex operator/(const Complex &, const Complex &);
	friend Complex operator-(const Complex &, const Complex &);
	friend void output(Complex &);
	friend ostream &operator<<(ostream &, const Complex &); 
private:
	int real, vir;
};

Complex operator+(const Complex &a, const Complex &b) {
	return Complex(a.real + b.real, a.vir + b.vir);
}

Complex operator-(const Complex &a, const Complex &b) {
	return Complex(a.real - b.real, a.vir - b.vir);
}

Complex operator*(const Complex &a, const Complex &b) {
	return Complex(a.real * b.real, a.vir * b.vir);
}

Complex operator/(const Complex &a, const Complex &b) {
	return Complex(a.real / b.real, a.vir / b.vir);
}

void output(Complex &a) {
	cout << a.real << "\t" << a.vir << endl;
	return ;
}

ostream &operator<<(ostream &out, const Complex &a) {
	out << a.real << "\t" << a.vir;
	return out;
} 

int main() {
	Complex com(4, 5);
	output(com);
	cout << com + 5 << endl;
	cout << (++com)++ << endl;
	cout << com << endl;
	Complex com1(2, 3);
	cout << com * com1 << endl;
	
	
	return 0;
}



这篇关于C++友元函数学习笔记的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程