其实我是C++的新手.我尝试了一些东西(实际上是地图容器),但是它没有按照我想象的方式工作......在发布我的代码之前,我会很快解释它.
我创建了3个类:
ClassA ClassDerivedA ClassAnotherDerivedA
最后两个来自"ClassA".
我进一步创建了一张地图:
map<string,ClassA> test_map;
Run Code Online (Sandbox Code Playgroud)
我将一些对象(来自Type ClassDerivedA和ClassAnotherDerivedA)放入地图中.请记住:映射值来自"ClassA"类型.这只会因多态性而起作用.最后,我创建了一个迭代器,它在我的地图上运行,并将用户输入与地图中的键进行比较.如果它们匹配,它将调用一个名为"printOutput"的特定方法.
还有一个问题:虽然我将"printOutput"声明为"虚拟",但是唯一被调用的方法是我的基类,但为什么呢?这是代码:
#include <iostream>
#include <map>
using namespace std;
class ClassA
{
public:
virtual void printOutput() { cout << "ClassA" << endl; }
};
class ClassDerivedA : public ClassA
{
public:
void printOutput() { cout << "ClassDerivedA" << endl; }
};
class ClassAnotherDerivedA: public ClassA
{
public:
void printOutput() { cout << "ClassAnotherDerivedA" << endl; }
};
int main()
{
ClassDerivedA class_derived_a;
ClassAnotherDerivedA class_another_a;
map<string,ClassA> test_map;
test_map.insert(pair<string,ClassA>("deriveda", class_derived_a));
test_map.insert(pair<string,ClassA>("anothera", class_another_a)); …Run Code Online (Sandbox Code Playgroud) 我有几个类继承自一个主类。为了简单起见,我过度简化了类定义,使其简短明了。
class Animal {
protected:
string name;
public:
Animal(string name);
virtual string toString() { return "I am an animal"; }
};
Run Code Online (Sandbox Code Playgroud)
class Bird: public Animal {
private:
bool canFly;
public:
Bird(string name, bool canFly = true)
: Animal(name) // call the super class constructor with its parameter
{
this->canFly = canFly;
}
string toString() { return "I am a bird"; }
};
Run Code Online (Sandbox Code Playgroud)
class Insect: public Animal {
private:
int numberOfLegs;
public:
Insect(string name, int numberOfLegs) : …Run Code Online (Sandbox Code Playgroud)