调用Baseclass方法而不是子类中的方法

时间:2016-04-01 20:28:08

标签: c++

我创建了BaseClass和两个子类:SubOneSubTwo。之后我创建了一个名为MyCollection的集合,它将实例存储在一个向量中。

基类和子类都有方法getString。基类返回base,子类返回sub1sub2

编译期间我没有收到任何警告或错误。但由于某种原因,如果我尝试迭代向量,子类将返回" base"

#include <iostream>
#include <vector>

class BaseClass {

    public:

        BaseClass() {}

        std::string getString() {
            return "base";
        }

};

class SubOne : public BaseClass {

    public:

        SubOne() : BaseClass() {}

        std::string getString() {
            return "sub1";
        }

};

class SubTwo : public BaseClass {

    public:

        SubTwo() : BaseClass() {}

        std::string getString() {
            return "sub2";
        }

};

class MyCollection {

    private:

        std::vector<BaseClass> instances;

    public:

        MyCollection() {}


        void add(BaseClass & ins) {
            instances.push_back(ins);
        }

        std::string printString() {

            for(std::vector<BaseClass>::iterator it = instances.begin() ; it != instances.end(); ++it) {
                std::cout << it->getString() << std::endl;
            }

        }

};

int main() {

    MyCollection *coll = new MyCollection();

    SubOne* s1 = new SubOne();
    SubTwo* s2 = new SubTwo();

    coll->add(*s1);
    coll->add(*s2);

    coll->printString();

    return 0;

}

1 个答案:

答案 0 :(得分:1)

您忘记使用关键字virtual。也转换为指针(信用给长颈鹿队长)。

见下面的代码:

#include <iostream>
#include <vector>

class BaseClass {

public:

    BaseClass() {}

    virtual std::string getString() { // BINGO _!_!_!_!
        return "base";
    }

};

class SubOne : public BaseClass {

public:

    SubOne() : BaseClass() {}

    std::string getString() {
        return "sub1";
    }

};

class SubTwo : public BaseClass {

public:

    SubTwo() : BaseClass() {}

    std::string getString() {
        return "sub2";
    }

};

class MyCollection {

private:

    std::vector<BaseClass*> instances;

public:

    MyCollection() {}


    void add(BaseClass* ins) {
        instances.push_back(ins);
    }

    std::string printString() {

        for(std::vector<BaseClass*>::iterator it = instances.begin() ; it != instances.end(); ++it) {
            std::cout << (*it)->getString() << std::endl;
        }

    }

};

int main() {

MyCollection *coll = new MyCollection();

SubOne* s1 = new SubOne();
SubTwo* s2 = new SubTwo();

coll->add(s1);
coll->add(s2);

coll->printString();

return 0;

}