You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过void print()打印std::shared_ptr指向的Song对象?

解决std::shared_ptr调用成员函数print()的错误

错误原因

std::shared_ptr<Song>是智能指针容器,它本身并没有定义print()成员函数,你实现的print()是属于Song类的成员,所以必须先访问智能指针指向的底层Song对象,才能调用该函数。

解决方法

有两种常用方式访问智能指针指向的对象并调用成员函数:

  • 使用->操作符(推荐):智能指针重载了->运算符,可以直接用来调用底层对象的成员函数
    sp1->print();
    sp2->print();
    
  • 使用*解引用后用.操作符:先解引用智能指针得到底层对象,再用.调用成员
    (*sp1).print();
    (*sp2).print();
    

额外修正:完善print()函数的输出逻辑

你提供的print()函数存在语法错误,输出语句中"title"后面缺少了<<,会导致编译错误,修正后的print()函数如下:

void print()
{
    std::cout << "artist " << artist << " - title " << title << " end\n";
}

完整修正后的代码

struct MediaAsset
{
    virtual ~MediaAsset() = default; // 让基类成为多态类型
};

struct Song : public MediaAsset
{
    std::string artist;
    std::string title;

    Song(const std::string& artist_, const std::string& title_) :
        artist{ artist_ }, title{ title_ }
    {
        std::cout << "Song " << artist_ << " - " << title_ << " constructed\n";
    }

    ~Song()
    {
        std::cout << "~Song " << artist << " - " << title << " destructed\n";
    }

    void print()
    {
        std::cout << "artist " << artist << " - title " << title << " end\n";
    }
};

using namespace std;

void example1()
{
    auto sp1 = make_shared<Song>("poets","carnival");
    shared_ptr<Song> sp2(new Song("poets","late goodbye") );
    sp1->print(); // 使用->调用成员函数
    sp2->print();
}

内容的提问来源于stack exchange,提问作者Nazanin R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 00:52:25