c – 为什么将unique_ptr与数组一起使用会导致编译错误?

c – 为什么将unique_ptr与数组一起使用会导致编译错误?,第1张

概述为什么使用unique_ptr< string>项目;而不是原始指针字符串*项;抛出编译错误. #include <iostream>#include <memory>using namespace std;class myarray{ private: unique_ptr <string> items; //string *items; public: 为什么使用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数组的指针

@H_403_38@ 总结

以上是内存溢出为你收集整理的c – 为什么将unique_ptr与数组一起使用会导致编译错误?全部内容,希望文章能够帮你解决c – 为什么将unique_ptr与数组一起使用会导致编译错误?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1220095.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-05
下一篇2022-06-05

发表评论

登录后才能评论

评论列表(0条)

    保存