c++ - 重写派生类中基类私有(private)成员的行为,C++

标签 c++ inheritance constructor private

假设我有一个来自软件包的类,因此我没有办法更改设计,其形式如下:

class A
{
public:
  A(int degree) 
  {
    ...
    initialize_points();
    ...
  }
  ...
private:
  ...
  void initialize_points() 
  { 
    int number = 1;
    // proceed to do computations using the number specified above
    ...
  }
  ...
}

我需要的是上课B类似于类 A除了 number 之外的所有内容在函数 initialize_points() 中指定。比如说,我希望它是 34 而不是 1。

由于缺乏经验,我不太明白如何派生这样一个类 B (我应该这样做吗,也许最好将其编写为一个模仿 A 实现的新类?)来自类 A因为我想要覆盖其行为的函数是 private基类成员。

谢谢

最佳答案

简短的回答是,这在 C++ 中无法完成。派生类可以重写其基类所做的操作的主要机制是虚函数。除非基类定义了虚函数,否则在派生类中无法执行任何操作来重写它。

关于c++ - 重写派生类中基类私有(private)成员的行为,C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32576691/

相关文章:

c++ - 在 C++ 中可以使用构造函数将 2D Vector 初始化为单行吗?

python - 无法编译需要 C99 编译器 (AFAIU) 的 pyethash python 包。错误 - 无法打开包含文件 : 'alloca.h'

c++ - 哪个参数应该首先是 `old` 或 `new` ?

java - 如何重写父类的方法

c++ - 对对象的引用必须在构造函数基类/成员初始化列表中初始化

c++ - 错误 C2082 : redefinition of formal parameter 'tmp'

c++ - 在嵌套私有(private)类内部的外部类中使用 C++ 公共(public)变量

c++ - 无法将右值 std::array 转换为 std::span

java - 了解 Java 中的继承概念

c++ - 继承带有默认参数的构造函数?