我有這樣的代碼:簡單的運算符重載不起作用
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