【发布时间】:2012-05-04 22:02:39
【问题描述】:
有很多关于 C++ 中逗号运算符重载的帖子(问题)。 大多数答案建议不要使用逗号运算符重载。 我想编写一个语法与 Matlab 语言非常相似的 c++ 库。 基本对象是 Matrix MX。我希望能够让库的最终用户编写如下表达式:
MX a = b(i);// get b elements at indices i
b(i,j)= a; // set elements of b at indices i,j.
我知道如何使用保存指向 MX 对象的指针并保存索引 i,j 对象的代理类来使 setter 和 getter 像上面所写的那样工作。例如 b(i,j) 将创建一个代理对象 ProxMX(b,i,j)。然后我们定义一个方法将 ProxMX 分配给 MX 和 visversa(使用运算符 =),它们完成了获取和设置 b 元素的艰巨工作。
我需要帮助来进行函数调用,例如:
(x,y,z)= ff(a,b,c)
其中 a、b、c 是输入参数(MX 对象),x、y、z 是输出参数。 如果上述语法是不可能的,我可以考虑这样的语法:
ff((a,b,c), (x,y,z) )
我开始编写这个测试代码:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
class MX {// Matrix
public:
MX(double va) {
elem=va;// only one double for the moment to test the syntaxe
}
MX &operator ()(MX idx){ // get & set MX(i)
return *this;//
};
MX &operator ()(MX idx1,MX idx2) { // get set MX(i,j)
return *this;
} ;
friend ostream &operator<<(ostream &stream, MX a);
double elem;
};
ostream &operator<<(ostream &stream, MX a)
{
stream << a.elem ;
return stream;
}
typedef vector<const MX > MXR;
class ArgList { // Proxy
public:
//ArgList(const MX& a){
// data.push_back(a);
//}
ArgList() {};
ArgList& operator , (const MX &a){
data.push_back(a);
return *this;
}
ArgList& operator =(ArgList& ins){
for (int i=0 ;i <ins.data.size();i++)
(this->data[i]).elem=ins.data[i].elem;
return *this;
};
MXR data;
};
ArgList operator , (const MX& a, const MX& b){
ArgList out;
out.data.push_back(a);
out.data.push_back(b);
return out;
}
ArgList ff(ArgList argins)
{
int n = argins.data.size();
MX a= argins.data[0];
MX b= argins.data[1];
MX x(a.elem+1.0);
MX y(b.elem+10.0);
MX z(a.elem+b.elem);
return ( x, y , z);
}
void gg(ArgList argins, ArgList &argout)
{
int n = argins.data.size();
MX a= argins.data[0];
MX b= argins.data[1];
MX x(a.elem+1.0);
MX y(b.elem+10.0);
MX z(a.elem+b.elem);
argout = ( x, y , z);
}
int _tmain(int argc, _TCHAR* argv[])
{
MX a(1.0);MX b(2.0);MX c(3.0);
MX aa = a(MX(3.0));
aa(MX(2.0),MX(3.0))=MX(5.0);
cout << "a=" << a << ",b=" << b << ",c=" << c << endl;
MX x(0.0);MX y(0.0);MX z(0.0);
cout << "x=" << x << ",y=" << y << ",z=" << z << endl;
(x,y,z)= ff((a , b, c ));
cout << "x=" << x << ",y=" << y << ",z=" << z << endl;
gg((a,b,c) , (x,y,z));
cout << "x=" << x << ",y=" << y << ",z=" << z << endl;
return 0;
}
此代码使用 VS2010 Express 编译和运行没有错误:)。但正如预期的那样,它没有给出预期的结果,因为我需要在 ArgList 中保存对变量的引用,而不是将对象复制到向量中。我知道我们不能使用 std::vector 作为对象引用的容器。
为了使这些表达式可写并在 c++ 代码中工作的任何帮助。 谢谢。
【问题讨论】:
-
您能否详细说明您的实际问题?它的行为不符合您的预期?除了
std::vector,您还需要其他容器吗?还有什么? -
我需要帮助才能使 (x,y,z)=ff((a,b,c)) 等表达式在 C++ 中调用函数。我的第一个测试代码让我认为接受对 ojects 的引用的容器可能是正确的方向。但我不是sur。
-
我已经看过 Blitz++,我认为在 c++ 中制作索引运算符“a la Matlab”是可能的。但我不认为 c++ 中的函数调用 à la Matlab 已经完成。
标签: c++ reference operator-overloading comma