0
我想了解,如果我的錯誤來自設計問題或代碼錯誤。我的搜索指出我切片問題,但我不認爲這是問題在這裏。Poylmorphism,在構造函數中使用的重寫方法 - C++
#include <string>
#include <iostream>
#include <vector>
class BaseA {
public:
BaseA(const std::string &n)
: name(n)
{}
virtual ~BaseA()
{};
virtual void print() const
{
std::string str("");
str += name;
std::cout << str << std::endl;
}
protected:
std::string name;
};
class BaseB : public BaseA {
public:
BaseB(const std::string &n, const std::string &v)
: BaseA(n), value(v)
{
load();
}
virtual ~BaseB()
{};
virtual void load(){
c = 'B';
}
char getC() {
return c;
}
void print() const{
std::string str("");
str += name;
str += ' ';
str += value;
std::cout << str << std::endl;
}
protected:
char c;
private:
std::string value;
int data = 0;
};
class BaseC : public BaseB {
public:
BaseC(const std::string &n, const std::string &v)
: BaseB(n, v)
{
}
void load() override{
c = 'C';
}
};
int mainTest()
{
std::vector<BaseB*> vec;
vec.push_back(new BaseB("John", "singer"));
vec.push_back(new BaseC("Raoul", "wannabe"));
for (BaseB *obj : vec)
{
obj->print();
std::cout << "load class: " << obj->getC() << std::endl;
}
return(0);
};
我希望的結果是:
John singer
load class: B
Raoul wannabe
load class: C
,但我得到B中兩者。這是否意味着在構造函數中,不可能使用重寫的類? 謝謝