我有这样的代码:简单的运算符重载不起作用
template <typename T>
class EasyPtr {
T* data;
public:
EasyPtr(T* data): data(data){}
EasyPtr(const EasyPtr<T>&)=delete;
EasyPtr(EasyPtr<T>&&) = delete;
~EasyPtr(){
delete data;
}
operator T*(){
return data;
}
EasyPtr & operator = (T* data) {
this -> data = data;
}
T& operator *() {
return *data;
}
T& operator [](size_t pos) {
return data[pos];
}
};
int main(){
EasyPtr<int> p = new int[10];
return 0;
}
令人惊讶的是给了错误:
In file included from easy_ptr_test.cpp:1:0:
./easy_ptr.hpp:23:20: error: declaration of ‘operator[]’ as non-function
./easy_ptr.hpp:23:18: error: expected ‘;’ at end of member declaration
./easy_ptr.hpp:23:27: error: expected ‘)’ before ‘pos’
easy_ptr_test.cpp: In function ‘int main()’:
easy_ptr_test.cpp:4:32: error: use of deleted function ‘EasyPtr<T>::EasyPtr(EasyPtr<T>&&) [with T = int]’
In file included from easy_ptr_test.cpp:1:0:
./easy_ptr.hpp:10:5: error: declared here
这显然是一个函数声明......不明白为什么。也许在某个地方有一个愚蠢的错误。
您的赋值运算符缺少返回语句。 –
@ K-ballo多数民众赞成在一个问题......但它给我在修复它后出现同样的错误 – texasbruce
该行主要隐含地构建了一个临时的'EasyPtr'在右侧。该临时可以移动到“p”中。临时移动到“p”的行为甚至可以被忽略,但为了实现这一点,移动构造函数仍然必须可访问,因此也是错误。如果将其更改为'EasyPtr p(new int [10])',它应该可以工作。 –
0x499602D2