c++ - 如何在类中使用结构的 std::unique_ptr?
问题描述
如何std::unique_ptr
在类中使用结构的 a ?像这样的东西,例如:
#include <cstdio>
#include <memory>
int main(void)
{
struct a_struct
{
char a_char;
};
class A_class
{
public:
A_class()
{
this->my_ptr.a_char = 'A';
}
void A_class_function()
{
printf("%c\n",this->my_ptr.a_char);
}
~A_class()
{
}
private:
std::unique_ptr<a_struct> my_ptr(new a_struct);
};
A_class My_class;
My_class.A_class_function();
My_class.~A_class();
return(0);
}
编译时,它会返回此错误,我不知道该怎么做:
ptr_test.cpp: In function ‘int main()’:
ptr_test.cpp:27:39: error: expected identifier before ‘new’
std::unique_ptr<a_struct> my_ptr(new a_struct);
^~~
ptr_test.cpp:27:39: error: expected ‘,’ or ‘...’ before ‘new’
ptr_test.cpp: In constructor ‘main()::A_class::A_class()’:
ptr_test.cpp:16:14: error: invalid use of member function ‘std::unique_ptr<main()::a_struct> main()::A_class::my_ptr(int)’ (did you forget the ‘()’ ?)
this->my_ptr.a_char = 'A';
~~~~~~^~~~~~
ptr_test.cpp: In member function ‘void main()::A_class::A_class_function()’:
ptr_test.cpp:20:28: error: invalid use of member function ‘std::unique_ptr<main()::a_struct> main()::A_class::my_ptr(int)’ (did you forget the ‘()’ ?)
printf("%c\n",this->my_ptr.a_char);
我该如何解决?我该怎么做这样的事情?
解决方案
对于第一个错误,您无法使用您尝试使用的构造函数语法在类声明中初始化类成员。
使用花括号代替括号:
class A_class
{
...
private:
std::unique_ptr<a_struct> my_ptr{new a_struct};
};
或者,如果您有 C++14 编译器:
class A_class
{
...
private:
std::unique_ptr<a_struct> my_ptr = std::make_unique<a_struct>();
};
否则,请改用A_class
构造函数的成员初始化列表:
class A_class
{
public:
A_class() : my_ptr(new a_struct)
{
...
}
...
private:
std::unique_ptr<a_struct> my_ptr;
};
对于其他错误,a_char
is 的成员a_struct
, not std::unique_ptr
,因此您需要使用my_ptr->a_char
而不是访问它my_ptr.a_char
。
this->my_ptr->a_char = 'A';
...
printf("%c\n", this->my_ptr->a_char);
推荐阅读
- python-3.x - 如何比较一个类的实例
- spring - 需要从 Spring Cloud Gateway 路由中的 OAuth2User 获取经过身份验证的用户名
- javascript - CSS - 图像隐藏在溢出区域
- python - IndexError:列表索引超出范围 - python 错误
- flask - 如何让文本在 Bootstrap 中环绕多个列
- ios - 如何在 Objective-C 中更改字符串数组中的子字符串?
- github - 如何使用 README.md 文件中的可点击链接调整图像大小?
- python - 如何在没有默认行填充颜色的情况下构建 Bokeh 数据表?
- html - 如何在 HTML 中水平排列列表
- r - 我怎么知道这段代码正在运行什么 arima 模型?