小编use*_*982的帖子

覆盖构造函数c ++

我有抽象的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)

但它不起作用.我的问题有什么可能的解决方案吗?

c++ inheritance constructor

1
推荐指数
1
解决办法
1万
查看次数

标签 统计

c++ ×1

constructor ×1

inheritance ×1