创建一个 const share_ptr;成员
我有许多从纯虚拟基派生的类:
class base {
public:
virtual int f() = 0;
};
class derived_0 : public base {
public:
int f() {return 0;}
};
class derived_1 : public base {
public:
int f() {return 1;}
};
为了简洁起见,我只放置了两个派生类,但实际上我有更多类。
我想创建一个具有指向基类的 const 共享指针的类。我想执行以下操作,但不能,因为我必须初始化初始化列表中的 const 指针:
class C{
public:
C(bool type) {
if(type) {
derived_0* xx = new derived_0;
x = shared_ptr<base>( xx );
}
else {
derived_1* xx = new derived1;
x = shared_ptr<base>( xx );
}
}
private:
const share_ptr<base> x;
};
如何获得此功能?
I have a number of classes that derive from a pure virtal base:
class base {
public:
virtual int f() = 0;
};
class derived_0 : public base {
public:
int f() {return 0;}
};
class derived_1 : public base {
public:
int f() {return 1;}
};
I only put two derived classes for brevity, but in practice I have more.
And I would like to create a class that has a const shared pointer to the base. I would like do to the following but I can't as I must initialize the const pointer in the initialization list:
class C{
public:
C(bool type) {
if(type) {
derived_0* xx = new derived_0;
x = shared_ptr<base>( xx );
}
else {
derived_1* xx = new derived1;
x = shared_ptr<base>( xx );
}
}
private:
const share_ptr<base> x;
};
How can I get this functionality?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将对象的创建封装在函数中,如下所示:
然后您可以在初始化列表中使用它:
You encapsulate the creation of the object in a function, like this:
And then you can use it in your initialization-list:
在像这个精确示例这样的简单情况下:(
是的,
static_cast
或至少其中之一是必要的。)在更一般的情况下,决策逻辑更复杂,您可以
可能想要创建一个返回
shared_ptr
的静态函数,例如:
这将允许任何可以想象的逻辑(以及一组更复杂的逻辑)
参数也是如此)。
In simple cases like this precise example:
(And yes, the
static_cast
, or at least one of them, are necessary.)In more general cases, where the decision logic is more complex, you
might want to create a static function which returns the
shared_ptr
,e.g.:
This will allow any imaginable logic (and a more complex set of
parameters as well).