创建常量share_ptr<pure_virtual_class>成员
Creating a const share_ptr<pure_virtual_class> member
我有许多派生自纯虚拟基的类:
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;
};
我怎样才能得到这个功能?
将对象的创建封装在函数中,如下所示:
shared_ptr<base> create_base(bool type) {
if(type) {
return make_shared<derived_0>();
}
else {
return make_shared<derived_1>();
}
}
然后你可以在你的初始化列表中使用它:
class C{
public:
C(bool type)
: x(create_base(type))
{}
private:
const share_ptr<base> x;
};
在像下面这样的简单情况下:
class C
{
shared_ptr<Base> const x;
public:
C( bool type )
: x( type
? static_cast<Base*>( new Derived_0 )
: static_cast<Base*>( new Derived_1 ) )
{
}
};
(是的,static_cast
,或至少其中一个,是必要的。)
在更一般的情况下,当决策逻辑更复杂时,您可能需要创建一个返回shared_ptr
的静态函数,例如:
class C
{
shared_ptr<Base> const x;
static shared_ptr<Base> makeSharedPtr( bool type );
public:
C( bool type )
: x( makeSharedPtr( type ) )
{
}
};
这将允许任何可以想象的逻辑(以及更复杂的逻辑集合)
相关文章:
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- C++核心准则 C35 对于接口类"A base class destructor should be either public and virtual, or protected and nonv
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- "Undefined class"作为is_base_of的论据
- 如何将class.cpp和class.hpp编译为一个.o文件
- 当我从下面的代码中删除关键字 virtual 时,它可以正常工作,否则会出现错误。在这里"virtual"字的意义是什么?
- '{'标记之前的预期类名,然后在预声明时无效使用不完整的类型'class class_name'
- 如何使用"derived input class"创建派生类?
- 错误:"Left of getValue must have class/struct/union"
- ' class a : b ' 和 ' class a : public b ' 之间的继承类不同
- Pybind11 Class Definition
- 在C++中使用没有合作伙伴Class/Cpp文件的头文件是否实用
- C2011 'CMemDC':Visual Studio 2019中的'class'类型重新定义
- TypeError: [c++ addon class] 不是构造函数
- C++ class template
- 当初始值设定项是基类名时'initializer does not name a non-static data member or base class'错误
- Clearing Class Foo with new(pFoo) Foo()
- C++ class vs a library
- "virtual A* someMethod"与"virtual class A* someMethod"
- "virtual base class in the case of multilevel inheritance"有意义吗