首页 > 解决方案 > 如何在类中使用结构的 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);

我该如何解决?我该怎么做这样的事情?

标签: c++classstructunique-ptr

解决方案


对于第一个错误,您无法使用您尝试使用的构造函数语法在类声明中初始化类成员。

使用花括号代替括号:

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_charis 的成员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);

推荐阅读