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

本文介绍了一个使用C++智能指针shared_ptr进行类间对象传递的示例,展示了如何创建并利用Base类对象来初始化fcn2类,并通过fcn2类的方法获取Base类对象的数据。

背景:
两个 类,类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;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值