c++ - 如何在结构上使用 std::unique_ptr?
问题描述
标题说了大部分,我该怎么做?我在谷歌上搜索了一下,没有人告诉我它不能完成,但也没有人解释如何去做。
在这里获取这段代码:
#include <cstdio>
#include <memory>
int main(void)
{
struct a_struct
{
char first;
int second;
float third;
};
std::unique_ptr<a_struct> my_ptr(new a_struct);
my_ptr.first = "A";
my_ptr.second = 2;
my_ptr.third = 3.00;
printf("%c\n%i\n%f\n",my_ptr.first, my_ptr.second, my_ptr.third);
return(0);
}
正如可以回答这个问题的人已经知道的那样,这不起作用,甚至无法编译。
我的问题是如何制作这样的作品?
编译错误(使用 g++-7)看起来像
baduniqueptr6.cpp: In function ‘int main()’:
baduniqueptr6.cpp:15:12: error: ‘class std::unique_ptr<main()::a_struct>’ has no member named ‘first’
my_ptr.first = "A";
^~~~~
baduniqueptr6.cpp:16:12: error: ‘class std::unique_ptr<main()::a_struct>’ has no member named ‘second’
my_ptr.second = 2;
^~~~~~
baduniqueptr6.cpp:17:12: error: ‘class std::unique_ptr<main()::a_struct>’ has no member named ‘third’
my_ptr.third = 3.00;
^~~~~
baduniqueptr6.cpp:19:34: error: ‘class std::unique_ptr<main()::a_struct>’ has no member named ‘first’
printf("%c\n%i\n%f\n",my_ptr.first, my_ptr.second, my_ptr.third);
^~~~~
baduniqueptr6.cpp:19:48: error: ‘class std::unique_ptr<main()::a_struct>’ has no member named ‘second’
printf("%c\n%i\n%f\n",my_ptr.first, my_ptr.second, my_ptr.third);
^~~~~~
baduniqueptr6.cpp:19:63: error: ‘class std::unique_ptr<main()::a_struct>’ has no member named ‘third’
printf("%c\n%i\n%f\n",my_ptr.first, my_ptr.second, my_ptr.third);
^~~~~
解决方案
您应该使用->
而不是.
,std::unique_ptr
是一个智能指针,其行为类似于原始指针。
my_ptr->first = 'A';
my_ptr->second = 2;
my_ptr->third = 3.00;
printf("%c\n%i\n%f\n",my_ptr->first, my_ptr->second, my_ptr->third);
或者您可以使用operator*
to 取消引用指针,然后您可以使用operator.
,这也与原始指针相同。
(*my_ptr).first = 'A';
(*my_ptr).second = 2;
(*my_ptr).third = 3.00;
printf("%c\n%i\n%f\n",(*my_ptr).first, (*my_ptr).second, (*my_ptr).third);
PS:您应该将"A"
(这是一个c风格的字符串)更改为'A'
(这是一个char
)。
推荐阅读
- teradata - 创建表没有预期的行数
- python - 基于熊猫特定条件的分组计数和比率
- python - 在 python 中保存模型而不使用 sklearn
- java - 在另一个类错误中使用一个类的对象数组和方法 - JAVA
- html - 具有相同最大宽度的 2 个 div 显示不同的宽度
- android - 无法从 firebase 检索图像
- sqlite - 添加新表 Flutter 后 sqflite 在 Android 上崩溃
- tizen - 在 tizen 可穿戴应用程序中大约一个小时后获取 GPS 的 LOCATIONS_ERROR_SERVICE_NOT_AVAILABLE
- elixir - Ecto(Phoenix)中的外键数组
- javascript - Chart.js 如何从 json 插入值