#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include <bitset>
#include <cmath>
#include <memory>
using namespace std;
class base {
private:
int value;
public:
base(int v) : value(v) {
printf("base constructor called\n");
}
virtual ~base(){
value = 0;
printf("base destructor called\n");
}
int getValue() {
printf("base value return: %d\n", value);
return value;
}
void setValue(int _val) {
printf("base value change to: %d\n", _val);
value = _val;
}
};
class derived : public base {
private:
int multi;
public:
derived(int v, int b) : base(b), multi(v) {
printf("derived constructor called\n");
}
~derived() {
printf("derived destructor called\n");
}
int domul() {
return multi * getValue();
}
void setMul(int _val) {
multi = _val;
}
};
int main(int argc, char* argv[]){
std::shared_ptr<derived> de = std::make_shared<derived>(10, -1);
std::shared_ptr<base>b = dynamic_pointer_cast<base>(de);
b->getValue();
std::shared_ptr<derived> dee = dynamic_pointer_cast<derived>(b);
cout << "mul:" << dee->domul() << endl;
dee->setValue(2);
dee->setMul(1);
cout << "mul:" << dee->domul() << endl;
dee = nullptr;
b = nullptr;
de = nullptr;
return 0;
}
C++ cast between base class and derived class with shared_ptr
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...