我正在实现一个模板化的矢量类(不是数据容器,而是线性代数意义上的矢量),每当我在运算符重载中引用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>
)。
此外,此行中的重载+运算符函数无法识别复制构造函数:
VecXd<T> temp = *this;
帮助?
答案 0 :(得分:30)
为了能够在const
对象上调用函数,您需要向编译器承诺该函数不会修改该对象。为此,您可以在参数列表后面用关键字const
标记该函数。例如,要使getDimension
成为const
成员函数,您可以将其更改为:
const ULL getDimension() const { return dimension; }
(请注意,返回类型中的const
绝对没有效果,所以你应该摆脱它)