我是shared_ptr struff的新手。所以这可能是一个愚蠢的问题,但我不知道我得到的错误。
#include<iostream>
#include<vector>
#include<memory>
#include<algorithm>
using namespace std;
class base
{
public:
base() { cout<<" base::ctor "<<endl; }
virtual void print() { cout<<" base::print "<<endl; }
virtual ~base() { cout<<" base::dtor "<<endl; }
};
class derived : public base
{
public:
derived() { cout<<" derived:ctor "<<endl; }
void print() { cout<<" derived::print "<<endl; }
~derived() { cout<<" derived::dtor "<<endl; }
};
typedef shared_ptr<base> sPtr;
int main()
{
vector<sPtr> v;
v.push_back(make_shared<derived>());
cout<<endl;
v.push_back(make_shared<derived>());
cout<<endl;
// for_each(v.begin(), v.end(), [](sPtr sp) { sp.print(); });
for(auto elem : v)
elem.print();
return 0;
}
错误:
sharedPtr.cpp: In function ‘int main()’:
sharedPtr.cpp:34:14: error: ‘class std::shared_ptr<base>’ has no member named ‘print’
elem.print();
^
由于理解有限,elem应该是类型&#34; base&#34;的共享指针,应该调用派生类的打印,因为它是一个虚函数。
此代码有什么问题?