覆盖派生 class 中基 class 私有成员的行为,C++
Override the behavior of base class private member in a derived class, C++
假设我有一个来自软件包的 class,所以我没有办法更改设计,它具有以下形式:
class A
{
public:
A(int degree)
{
...
initialize_points();
...
}
...
private:
...
void initialize_points()
{
int number = 1;
// proceed to do computations using the number specified above
...
}
...
}
我需要的是 class B
在所有方面都类似于 class A
除了函数 initialize_points()
。比如说,我希望它是 34 而不是 1。
由于缺乏经验,我不太明白我是如何推导出这样一个 class B
(我应该这样做,也许最好把它写成一个新的 class 从 class A
模仿 A
?) 的实现,因为我想覆盖的函数是基 private
的成员 class.
谢谢
简短的回答是这不能在 C++ 中完成。派生 class 可以覆盖其基础 class 所做的事情的主要机制是虚函数。除非基础 class 定义虚函数,否则在派生 class 中无法覆盖它。
假设我有一个来自软件包的 class,所以我没有办法更改设计,它具有以下形式:
class A
{
public:
A(int degree)
{
...
initialize_points();
...
}
...
private:
...
void initialize_points()
{
int number = 1;
// proceed to do computations using the number specified above
...
}
...
}
我需要的是 class B
在所有方面都类似于 class A
除了函数 initialize_points()
。比如说,我希望它是 34 而不是 1。
由于缺乏经验,我不太明白我是如何推导出这样一个 class B
(我应该这样做,也许最好把它写成一个新的 class 从 class A
模仿 A
?) 的实现,因为我想覆盖的函数是基 private
的成员 class.
谢谢
简短的回答是这不能在 C++ 中完成。派生 class 可以覆盖其基础 class 所做的事情的主要机制是虚函数。除非基础 class 定义虚函数,否则在派生 class 中无法覆盖它。