如何通过void print()打印std::shared_ptr指向的Song对象?
错误原因
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
相关产品推荐
相关产品推荐

