【C++】使用make_unique智能指针向类中传递数据

背景:
两个 类,类Base和类fcn2

将Base传递进fcn2中

#include <iostream>
#include <memory>

using namespace std;
#define PI 3.1415926
class Base
{
public:
    Base()
    {
    }
    double height = 3;
    double length = 2;
    double width = 1;

    ~Base()
    {
    }
};

class fcn2
{
public:
    shared_ptr<Base> Base_;

    fcn2(shared_ptr<Base> Base)
    {
        this->Base_ = Base;
        cout << Base_->length << endl;
        cout << "ssss" << endl;
    }

    void getValue()
    {
        double output;
        output = Base_->height * Base_->length * Base_->width;
        cout << output << endl;
    }

    ~fcn2()
    {
    }
};

void func1(shared_ptr<Base> sp)
{
    cout << "func1 num: " << sp->length << " count: " << sp->height << endl;
}

int main()
{
    // auto Base_ = shared_ptr<Base>(new Base);
    auto Base_ = make_unique<Base>();

    Base_->height = 11.0;
    Base_->length = 21.0;
    Base_->width = 31.0;

    cout << Base_->height << endl;

    fcn2 fcn2_(move(Base_));

    fcn2_.getValue();

    return 0;
}
posted @ 2022-05-27 14:04  你看不见我的blog  阅读(28)  评论(0编辑  收藏  举报  来源