我正在实现模板化的矢量类(不是数据容器,而是线性代数意义上的矢量),每当我rhs
在运算符重载中引用时,都会遇到很多错误。另外,我的复制构造函数似乎不起作用。
#ifndef __VecXd__VecXd__
#define __VecXd__VecXd__
#define ULL unsigned long long
#include <iostream>
using namespace std;
template <class T>
class VecXd
{
public:
explicit VecXd(ULL newDimension = 1) { dimension = newDimension; vector = new T[newDimension];}
VecXd(const VecXd<T> &rhs);
VecXd<T>& operator=(const VecXd<T> &rhs);
const VecXd<T> operator+(const VecXd<T> &rhs) const;
VecXd<T>& operator+=(const VecXd<T> &rhs);
friend ostream& operator<<(ostream &out, VecXd<T> vec);
friend istream& operator>>(istream &in, VecXd<T>& vec);
~VecXd() { delete[] vector; }
const ULL getDimension() { return dimension; }
const T itemAtIndex(ULL index) { if(index >= dimension) throw 1; return vector[index]; }
private:
ULL dimension;
T *vector;
};
template <class T>
VecXd<T>::VecXd(const VecXd<T> &rhs)
{
dimension = rhs.getDimension();
vector = new T[dimension];
for (ULL i = 0; i < dimension; ++i)
vector[i] = rhs.itemAtIndex(i);
}
template <class T>
VecXd<T>& VecXd<T>::operator=(const VecXd<T> &rhs)
{
if (this != &rhs)
{
if (dimension != rhs.getDimension())
{
delete [] vector;
dimension = rhs.getDimension();
vector = new T[dimension];
}
for (ULL i = 0; i < dimension; ++i)
vector[i] = rhs.itemAtIndex(i);
}
return *this;
}
template <class T>
VecXd<T>& VecXd<T>::operator+=(const VecXd<T> &rhs)
{
if (dimension != rhs.getDimension())
{
cout << "\nCannot perform addition. Vectors do not have the same dimensions.\n";
throw 1;
}
else
{
for (ULL i = 0; i < dimension; ++i)
vector[i] += rhs[i];
}
return *this;
}
template <class T>
const VecXd<T> VecXd<T>::operator+(const VecXd<T> &rhs) const
{
VecXd<T> temp = *this;
temp += rhs;
return temp;
}
template <class T>
ostream& operator<<(ostream &outs, VecXd<T> vec)
{
for (ULL i = 0; i < vec.dimension; ++i)
out << vec.vector[i] << (i+1 < vec.dimension ? " " : "");
return out;
}
template <class T>
istream& operator>>(istream &in, VecXd<T> &vec)
{
ULL newDim = 1;
cin >> newDim;
if (!cin.good())
{
cout << "\nImproper input.\n";
throw 1;
}
else
{
delete [] vec.vector;
vec.dimension = newDim;
vec.vector = new T[vec.dimension];
for (ULL i = 0; i < vec.dimension; ++i)
in >> vec.vector[i];
}
return in;
}
#endif /* defined(__VecXd__VecXd__) */
我收到这种样式的错误:
Member function 'getDimension' not viable: 'this' argument has type 'const VecXd<int>', but function is not marked const
每次rhs
调用函数(例如getDimension()
或itemAtIndex()
)时都会发生这种情况;出现两个错误(一次为VecXd<int>
,另一个为VecXd<int>
)。
另外,此行的重载+ operator函数中无法识别复制构造函数:
VecXd<T> temp = *this;
帮助?
为了能够在const
对象上调用函数,您需要向编译器保证该函数不会修改该对象。为此,您可以在函数的const
参数列表之后用关键字标记该函数。例如,为了使getDimension
一个const
成员函数,你将其更改为:
const ULL getDimension() const { return dimension; }
(请注意,const
返回类型中的in绝对无效,因此您应该摆脱它)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句