Log*_*thm 3 c++ inheritance overriding c++11
我正在开展一个项目,其中有一系列儿童课程。我想从数组中调用重写的子函数,但它调用了父函数。
#include <iostream>
class Parent {
public:
Parent(){}
void print() {
std::cout << "I'm the parent!" << std::endl;
}
};
class ChildOne : public Parent {
public:
ChildOne(){}
void print() {
std::cout << "I'm childOne!" << std::endl;
}
};
class ChildTwo : public Parent {
public:
ChildTwo() {}
void print() {
std::cout << "I'm childTwo!" << std::endl;
}
};
int main(int argc, char const *argv[]) {
Parent arr[] = {ChildOne(), ChildTwo()};
int n = 2;
for(int i = 0; i < n; i++) {
arr[i].print();
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我得到的输出是
I'm the parent!
I'm the parent!
Run Code Online (Sandbox Code Playgroud)
我想要的输出在哪里
I'm childOne!
I'm childTwo!
Run Code Online (Sandbox Code Playgroud)
首先, 的成员函数Parent需要是virtual。
class Parent
{
public:
Parent(){}
virtual void print() {std::cout << "I'm the parent!" << std::endl;};
};
Run Code Online (Sandbox Code Playgroud)
然后孩子们需要覆盖它。在C++11及更高版本中,建议使用override
class ChildOne : public Parent
{
public:
ChildOne(){}
void print() override {std::cout << "I'm childOne!" << std::endl;};
};
Run Code Online (Sandbox Code Playgroud)
要解决的第二件事是您的代码main()
Run Code Online (Sandbox Code Playgroud)Parent arr[] = {ChildOne(), ChildTwo()};
Parent通过切片 初始化两个对象 iearr[0]和arr[1]都是类型Parent,而不是ChildOne或ChildTwo。
为了解决这个问题,必须arr是一个指针数组,并进行相应的初始化。
Parent *arr[] = {new ChildOne(), new ChildTwo()};
Run Code Online (Sandbox Code Playgroud)
可以跟进
for(int i = 0; i < 2; i++)
{
arr[i]->print();
}
for(int i = 0; i < 2; i++) // to avoid a memory leak
{
delete arr[i];
}
// don't use elements of `arr` here
Run Code Online (Sandbox Code Playgroud)
更好的方法(C++11及更高版本)是编写是从标准头main()使用)std::unique_ptr<memory>
std::unique_ptr<Parent> arr[] = {new ChildOne(), new ChildTwo()};
Run Code Online (Sandbox Code Playgroud)
这允许取消循环来释放 的元素arr。arr在 C++14 及更高版本中,可以使用 来创建中的对象std::make_unique()。
| 归档时间: |
|
| 查看次数: |
1321 次 |
| 最近记录: |