我想在我的基类中有一个typedef专门用于从这个基类派生的每个类。代码:
template<class X>
class SharedPointer
{
public:
X* data;
SharedPtr(X *val)
{
data = val;
}
};
template<class T=Base> /* default type, I know this is a mistake.
The reason to have this here is to just indicate that the default argument
should be Base itself. so it'll have a Base type of shared pointer. */
class Base
{
public:
typedef SharedPointer<T> MyTypeOfPtr;
virtual MyTypeOfPtr Func()
{
Base *b = new Base;
return MyTypeOfPtr(b);
}
};
class Derived : Base<Derived>
{
public:
MyTypeOfPtr Func()
{
Derived *d = new Derived;
return MyTypeOfPtr(d);
}
};
main()
{
Base b;
Base::MyTypeOfPtr ptr1 = b.Func();
Derived d;
Derived::MyTypeOfPtr ptr2 = d.Func();
}
但这不会编译。有没有办法拥有这个功能?
答案 0 :(得分:2)
你必须正确地获得各种细节:
拼写:&#34; SharedPointer&#34;或&#34; SharedPtr&#34;?
模板和课程不是一回事,所以你不能class T = Base
:T
是一个班级,Base
不是&#39;吨。此外,您无法参考自己,因此即使class T = Base<T>
也无效。删除默认类型。
默认情况下,类继承是私有的,所以说class Derived : public Base<Derived>
。
制作SharedPointer
public的构造函数。
Base::Func()
毫无意义;也许应该说new T
。
我应该认真地建议你从简单的例子开始,慢慢积累。