【发布时间】:2009-04-14 04:57:08
【问题描述】:
我想创建一个行为类似于数学向量的类的集合,以便将对象乘以标量将每个字段乘以该数量等。问题是我希望字段具有实际名称,而不是作为索引处理。
我最初的想法是创建一个具有重载的基类 Rn,然后创建具有漂亮名称的派生类。像这样的:
#include <iostream>
#include <algorithm>
using namespace std;
template<int N, class X=double>
struct Base{
X xs[N];
Base(){};
Base(X *data){
copy(data, data+N, xs);
}
Base operator*= (double d){
for(int i=0; i<N; i++){
xs[i] *= d;
}
return *this;
}
Base operator* (double d){
Base answer = *this;
answer *= d;
return answer;
}
//also operators for +=, +, multiplication from left, maybe [] too
};
struct Derived : public Base<2>{
Derived(double a, double b){
foo() = a;
bar() = b;
}
double &foo(){ return xs[0]; }
double &bar(){ return xs[1]; }
};
int main()
{
//this is OK:
double data[2] = {0.0, 2.0};
Base<2> b(data);
b = b*17.0;
cout << b.xs[0] << endl;
//I can't do this:
Derived x(0.0, 2.0);
x = x*17.0;
cout << x.foo() << endl;
return 0;
}
每当我尝试使用需要复制的运算符时,都会出现编译器错误。 gcc 给了我以下编译器错误:
teste.cpp: In function ‘int main()’:
teste.cpp:52: error: no match for ‘operator=’ in ‘x = x.Derived::<anonymous>.Base<N, X>::operator* [with int N = 2, X = double](1.7e+1)’
teste.cpp:31: note: candidates are: Derived& Derived::operator=(const Derived&)
我认为问题在于重载函数处理的 Base 对象无法转换为 Derived 对象,因此我无法在派生类中使用它们。但是,我想不出解决方案。有没有办法解决这个问题,还是我应该使用完全不同的方法?
额外问题:有什么方法可以使用 std::valarray 来避免输入大量的运算符重载?
【问题讨论】: