C++ 逗号运算符重载,blitz 库分析

blitz 演示程序有下面这样的代码。看到矩阵A、B的赋值语句的写法,我惊呆了。第一时间想到应该是用了逗号运算符重载。

#include <blitz/array.h>
using namespace blitz;
int main()
{
	Array<float,2> A(3,3), B(3,3), C(3,3);
	A = 1, 0, 0,
		2, 2, 2,
		1, 0, 0;
	B = 0, 0, 7,
		0, 8, 0,
		9, 9, 9;
	C = A + B;
	cout << "A = " << A << endl
	<< "B = " << B << endl
	<< "C = " << C << endl;
	return 0;
}

自己写段代码框架模拟了一下,没写具体实现代码,通过这个框架能理解如何实现 blitz 的赋值方法。

#include <iostream>
using namespace std;

class List{
private:
public:
	List(){}
	List& operator = (int val){ 
		cout << "operator = (" << val << ")" << endl;
		return *this; 
	}
	List& operator , (int val){ 
		cout << "operator , (" << val << ")" << endl;
		return *this; }
};

int main(){
	List list;
	list = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;
	system("pause");
}

运行一下看看,

operator = (1)
operator , (2)
operator , (3)
operator , (4)
operator , (5)
operator , (6)
operator , (7)
operator , (8)
operator , (9)
operator , (10)
请按任意键继续. . .

万能的 C++ 确实牛叉!!!

发布了174 篇原创文章 · 获赞 80 · 访问量 35万+

猜你喜欢

转载自blog.csdn.net/quicmous/article/details/100702778