我 C++玩的不怎么样。尤其是继承。所以想多学习学习。
应用需求:
有一个基类对象,我想在它上面加一部分功能,就做了一个派生类(但派生类没法做到完美继承基类,因为其中基类有一堆的注册函数,搞定太复杂)。
于是,我就想,通过派生类指针 + 基类的对象,来实现功能的添加。
我的思路:
- 有个基类
- 有基类的对象,base_obj
- 声明了一个派生类,重写了基类的几个 virtual 方法
- 用派生类的指针 ptr_derived_obj 指向 base_obj
- 用 ptr_derived_obj 调用重写的派生类方法
我试了但是不工作不了
原型代码在这里
#include <iostream>
#include <string>
#include <memory>
using std::string;
using std::cout;
using std::endl;
using std::shared_ptr;
class Base {
public:
Base(const char * str): token(str) {}
virtual void addComment() { token+="is the most beautiful language!"; }
void speakOut() const { cout<<token<<endl; }
protected:
string token;
};
class Derived: public Base {
public:
Derived(const char* str): Base(str) {}
void addComment() { token="Python is the most beautiful language!"; }
};
int main() {
// ----- base_ptr call base_object -----
shared_ptr<Base> ptr_base_obj(new Base("C++"));
ptr_base_obj->addComment();
ptr_base_obj->speakOut();
// ----- derived_ptr call derived_object -----
shared_ptr<Derived> ptr_derived_obj(new Derived("PHP"));
ptr_derived_obj->addComment();
ptr_derived_obj->speakOut();
// ----- derived_ptr call base_object -----
shared_ptr<Base> ptr_base_obj2(new Base("PHP"));
// downcasting base to derived ptr
shared_ptr<Derived> ptr_derived_obj2 = std::dynamic_pointer_cast<Derived>(ptr_base_object2);
ptr_derived_obj2->addComment();
ptr_derived_obj2->speakOut();
return 0;
}
执行结果:
C++ is the most beautiful language!
Python is the most beautiful language!
Segmentation fault
-
想问,到底该怎么做,才能实现这个的需求。
-
另外,谁能把代码中 PHP is the most beautiful language!给输出出来?