Mut*_*aru 3 c++ struct unique-ptr c++11
标题说明了大部分内容,我该怎么做?我已经在Google上搜索了一下,没有任何东西告诉我它无法完成,但是也没有任何说明如何做到这一点。
在此处获取以下代码段:
#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);
}
Run Code Online (Sandbox Code Playgroud)
正如能够回答这个问题的人已经知道的那样,这行不通,甚至无法编译。
我的问题是我该如何做类似的工作?
编译错误(使用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);
^~~~~
Run Code Online (Sandbox Code Playgroud)
您应该使用->而不是.,它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);
Run Code Online (Sandbox Code Playgroud)
或者,可以使用operator*对指针的取消引用,然后可以使用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);
Run Code Online (Sandbox Code Playgroud)
PS:您应该将"A"(这是C样式的字符串)更改为'A'(是char)。
| 归档时间: |
|
| 查看次数: |
136 次 |
| 最近记录: |