C++函数调用运算符重载

C++函数调用运算符重载

我还不是很清楚它的具体价值,以后再更新。。。

函数调用运算符重载

  • 用在STL中
  • 十分灵活
  • 也称为仿函数
#include<iostream>
#include<string>
using namespace std;

class MyPrint
{
public:
	void operator()(string text)
	{
		cout << text << endl;
	}

};
void test01()
{
	//重载的()操作符 也称为仿函数
	MyPrint myFunc;
	myFunc("hello world");
}


class MyAdd
{
public:
	int operator()(int v1, int v2)
	{
		return v1 + v2;
	}
};

void test02()
{
	MyAdd add;
	int ret = add(10, 10);
	cout << "ret = " << ret << endl;

	//匿名对象调用  
	cout << "MyAdd()(100,100) = " << MyAdd()(100, 100) << endl;
}

int main() {

	test01();
	test02();

	system("pause");

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
C++中的运算符重载可以通过友元函数来实现。友元函数是定义在类外部的普通函数,但是可以访问类的所有私有成员。通过将运算符重载函数声明为类的友元函数,可以使该函数访问类的私有成员。 下面是一个示例代码,演示了如何通过友元函数实现运算符重载: ```c++ #include <iostream> class Complex { public: Complex(double real = 0.0, double imag = 0.0) : real_(real), imag_(imag) {} double real() const { return real_; } double imag() const { return imag_; } private: double real_; double imag_; friend Complex operator+(const Complex& c1, const Complex& c2); }; Complex operator+(const Complex& c1, const Complex& c2) { return Complex(c1.real_ + c2.real_, c1.imag_ + c2.imag_); } int main() { Complex c1(1.0, 2.0); Complex c2(3.0, 4.0); Complex c3 = c1 + c2; std::cout << "real: " << c3.real() << ", imag: " << c3.imag() << std::endl; return 0; } ``` 在上面的代码中,我们定义了一个Complex类,包含了两个私有成员变量real_和imag_,表示复数的实部和虚部。我们通过友元函数operator+来实现运算符重载,使得两个Complex对象可以通过"+"运算相加。在友元函数operator+中,我们可以访问Complex类的私有成员变量real_和imag_,从而实现了运算符重载。 在main函数中,我们创建了两个Complex对象c1和c2,并通过运算符重载将它们相加,最终得到一个新的Complex对象c3。我们可以通过调用c3的real()和imag()方法来获取它的实部和虚部。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

袁博特

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值