jeudi 23 mars 2017

Distinc derived class C++

I have a base class and two derived classes. Now I want to create a vector of base class. When I add new element, it checks which class of the new element. But in C++, there is no function like instanceOf, so I must add variable type to check. Here my piece of code.

class Element {
public:
    int getIndex() const {
        return index;
    }

    void setIndex(int index) {
        this->index = index;
    }

    const std::string& getMsg() const {
        return msg;
    }

    void setMsg(const std::string& msg) {
        this->msg = msg;
    }

    std::string toString() {
        std::stringstream sbuf;
        sbuf << "index: " << index << "\n";
        sbuf << "Message: " << msg << "\n";
        return sbuf.str();
    }

private:
    int index;
    int type;

    std::string msg;

};

Two derived class:

class This: public Element {
public:
    This():type(1){};
    ~This();

    const std::vector<std::string>& getArguments() const {
        return arguments;
    }

    void setArguments(const std::vector<std::string>& arguments) {
        this->arguments = arguments;
    }

    void add(std::string value) {
        arguments.push_back(value);
    }

private:
    std::vector<std::string> arguments;


};

class That: public Element {
public:
    That():type(2){};
    ~That();

    const std::string& getThatVal() const {
        return thatVal;
    }

    void setThatVal(const std::string& thatVal) {
        this->thatVal = thatVal;
    }

private:
    std::string thatVal;


};

In another class, I want to create the array of Element.

class Visitor {
private:
    int numOfThis = 0;
    int numOfThat = 0;
    std::vector<Element> vecEle;

public:
    void add(Element ele) {
        vecEle.push_back(ele);
        if (ele.type == 1) {
            numOfThis++;
        } else if (ele.type == 2) {
            numOfThat++;
        }
    }

    int getNumOfThat() const {
        return numOfThat;
    }

    int getNumOfThis() const {
        return numOfThis;
    }
};

My question is how to handle this better? is there a design pattern for this situation? Thanks

Aucun commentaire:

Enregistrer un commentaire