如何打印shared_ptr?我必须通过“void print”打印 sp1 和 sp2,但我不知道该怎么做。这是代码
struct MediaAsset
{
virtual ~MediaAsset() = default; // make it polymorphic
};
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()
{
//Complete to show information about the current object
}
};
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();
}
我写了
void print()
{
std::cout << "artist " << artist << " - " << "title" << title << " end\n";
}
这是我运行程序时收到的消息
错误:“类 std::shared_ptr”没有名为“print”的成员
print()
不是 shared_ptr
的方法。您需要取消引用 shared_ptr
才能访问 Song
对象,例如:
auto sp1 = make_shared<Song>("poets","carnival");
shared_ptr<Song> sp2(new Song("poets","late goodbye") );
sp1->print();
sp2->print();
或者:
auto sp1 = make_shared<Song>("poets","carnival");
shared_ptr<Song> sp2(new Song("poets","late goodbye") );
(*sp1).print();
(*sp2).print();