【发布时间】:2015-05-12 20:22:02
【问题描述】:
我正在尝试编译我的数组包装类,但我是 C++ 新手。我不断得到一系列与最后一个功能相关的信息:
第 81 行 没有参数列表的模板名称'warray'的无效使用
第 81 行 ISO C++ 禁止声明非类型的“参数”
第 81 行
第 83 行
rhs 未在此范围内声明 最后,第 86 行
rhs 未在此范围内声明 这个函数太混乱了,我想我实现的都是正确的。 IDK!请帮忙!#ifndef WARRAY
#define WARRAY
#include <iostream>
#include <stdexcept>
template <typename T>
class warray {
private:
unsigned int theSize;
T* theData;
public:
//will default to a size of 10 - bump to 10 if below
warray(unsigned int size = 10){
if(size < 10){
size = 10;
}
theSize = size;
theData = new T[theSize];
}
//copy
warray(const warray &rhs):theSize(rhs.theSize){
theData = new T[theSize];
//use assignment*this = rhs;
*this = rhs;
}
//assignment
warray & operator=(const warray &rhs){
//only resize array if lhs < than rhs//this also remedies
if(theSize < rhs.theSize){
delete [] theData;
theData = new T[rhs.theSize];
}
theSize = rhs.theSize;
for(unsigned int i = 0; i < theSize; ++i){
(*this);
}
return *this;
}
//destrctor
~warray(){
delete [] theData;
}
//operator+ will concatenate two arrays should be const
warray operator+(const warray &rhs) const{
warray toRet(theSize + rhs.size);
for(unsigned int i = 0; i < theSize; ++i){
toRet[i] = (*this)[i];
}
for(unsigned int i = 0; i < theSize; ++i){
toRet[i+theSize] = rhs[i];
}
return warray();
}
//operator[unsigned T index]
//will index and allow access to requested element
// - two versions, const and non-const
T operator[](unsigned int index) const{
if(index >= theSize){
throw std::out_of_range ("in operator [] ");
}
return theData[theSize];
}
//size
unsigned int size() const{
return theSize;
}
};
std::ostream &operator<< (std::ostream &os, const warray&<T> rhs){
os << "[ ";
for(unsigned i = 0; i < rhs.size()-1; ++i){
os << rhs[i] << " , ";
}
os << rhs[rhs.size() - 1] << " ]";
return os;
}
#endif
【问题讨论】:
-
是的,“T *theData [theSize];”是错的。您已将此标记为 C++ ...我建议您将两个数据属性替换为单个向量。
-
正如其他人回答的那样,您的问题是您如何声明
theData。还有一些其他注意事项:您的<<运算符应声明为friend并在类范围内移动;这条线还有什么作用:for(unsigned int i = 0; i < theSize; ++i) { (*this); }..??? .. 最后,不确定这是否是一项练习,但使用std::vector或其他序列容器之一(然后可以使用其他STL 序列功能,如std::fill和/或@ 987654328@)?? -
请不要编辑您的问题,以使之前给出的所有答案无效。这会让想要回答您的新问题的未来访问者感到非常困惑。
-
@TheDark 很抱歉,我已针对问题进行了调整,不会更改
-
@TheDark 可以再看看吗?