c – 为什么将unique_ptr与数组一起使用会导致编译错误?
发布时间:2020-12-16 10:25:58 所属栏目:百科 来源:网络整理
导读:为什么使用unique_ptr string项目;而不是原始指针字符串*项;抛出编译错误. #include iostream#include memoryusing namespace std;class myarray{ private: unique_ptr string items; //string *items; public: myarray (int size=20) : items (new string [
为什么使用unique_ptr< string>项目;而不是原始指针字符串*项;抛出编译错误.
#include <iostream> #include <memory> using namespace std; class myarray { private: unique_ptr <string> items; //string *items; public: myarray (int size=20) : items (new string [size] ) {} string& operator[] (const int index) { return items[index]; } }; int main() { myarray m1(200); myarray m2; m1[19] = "test"; cout << m1[19]; return 0; } 错误: subscript2.cpp: In member function ‘std::string& myarray::operator[](int)’: subscript2.cpp:15: error: no match for ‘operator[]’ in ‘((myarray*)this)->myarray::items[index]’ 解决方法
如果你想要一个指向动态分配的字符串数组的unique_ptr指针,你可能想要使用unique_ptr< T []>形式,即:
unique_ptr<string[]> items; 事实上: > unique_ptr< T>是指向T的单个实例的指针> unique_ptr< T []>是指向Ts数组的指针 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |