use*_*982 1 c++ inheritance constructor
我有抽象的A类
class A{
public:
A(dim) : dim_(dim);
private:
int dim_;
}
Run Code Online (Sandbox Code Playgroud)
和B级
class B : public A{
public:
B(int dim);
}
Run Code Online (Sandbox Code Playgroud)
我需要为类B制作构造函数,它只在dim> 1时才有效,否则抛出断言.
在这种情况下
B::B(int dim) : A(dim){
assert(dim > 1);
}
Run Code Online (Sandbox Code Playgroud)
它有效,但我认为这不是一个好的解决方案,因为A类的实例是创建和删除的.
比我为A类制作init-method:
class A{
public:
void init(int dim){
dim_ = dim;
}
A(int dim){
init(dim);
}
private:
int dim_;
}
Run Code Online (Sandbox Code Playgroud)
并更改B类的构造函数:
class B : public A {
public:
B(int dim){
assert(dim > 1);
init(dim);
}
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用.我的问题有什么可能的解决方案吗?
我想你可以写一个myint小班,确保int你通过的总是大于1:
struct myint
{
int data;
myint(int i) : data(i) { assert(data > 1); }
};
Run Code Online (Sandbox Code Playgroud)
现在在课堂上使用它:
class B : public A{
public:
B(myint dim) //this can still take int, due to implicit conversion!
: A(dim.data) { }
}
Run Code Online (Sandbox Code Playgroud)
请注意,您仍然可以构造B传递int,因为它将隐式转换为myint并且在转换发生时(隐式),它将测试断言,如果成功,那么您将能够传递dim.data给基类A.如果断言失败,您的程序将在进入基类构造函数之前中止(也不会在派生类中初始化任何内容).
您甚至可以将其概括为:
//Summary : gint<N> makes sure that data > N
template<int N>
struct gint //call it greater int
{
int data;
gint(int i) : data(i) { assert(data > N); } //Use N here!
};
Run Code Online (Sandbox Code Playgroud)
现在在课堂上使用它:
class B : public A{
public:
B(gint<1> dim) //the template argument 1 makes sure that dim.data > 1
: A(dim.data) { }
}
Run Code Online (Sandbox Code Playgroud)
如果您需要其他课程,例如:
class Xyz : public A{
public:
B(gint<10> dim) //gint<10> makes sure that dim.data > 10
: A(dim.data) { }
}
Run Code Online (Sandbox Code Playgroud)
很酷,不是吗?