首页 > 解决方案 > 这个C++代码的继承有什么问题

问题描述

这是我的代码:

class SimpleProduct {
    char look = 'x';
    string name = "Undefined";
    string type = "Undefined";
    string description = "Undefined";
public:
    char getLook() const {return look;}
    string getType() const {return type;}
    string getName() const {return name;}
    string getDescription() const {return description;}
    SimpleProduct(char look = 'x', string &&name = "Undefined", string &&type = "Undefined", string &&description = "Undefined");
    string toString() const;
};

class TallProduct : public SimpleProduct {
public:
    TallProduct(char look, string &&name = "Undefined", string &&type = "Undefined", string &&description = "Undefined");
    string toString() const;
};


inline SimpleProduct::SimpleProduct(char look, string &&name, string &&type, string &&description) :
        look(look), name(move(name)), type(move(type)), description(move(description)) {
}

inline string SimpleProduct::toString() const {
    ostringstream ost;
    if (this->getName() == "Space") {
        ost << "";
    } else {
        ost << "Look: " << this->getLook() << ", name: " << this->getName() << ", type: " << this->getType() << ", description: "
            << this->getDescription();
    }
    return ost.str();
};

inline TallProduct::TallProduct(char look, string &&name, string &&type, string &&description){
}

inline string TallProduct::toString() const {
    return "TALL | " + SimpleProduct::toString();
}

这是我的测试:

TEST(Test3, TallProduct) {
    SimpleProduct *product = new TallProduct('t', "Fresh sandwich", "sandwich", "check the expiration date");
    ASSERT_EQ("TALL | Look: t, name: Fresh sandwich, type: sandwich, description: check the expiration date",  product->toString());
}

我得到的结果总是这样:

"Look: x, name: Undefined, type: Undefined, description: Undefined"

虽然它应该是:

"TALL | Look: t, name: Fresh sandwich, type: sandwich, description: check the expiration date"

你能指导我在哪里做错了吗?我猜错误的部分是在调用方法周围的某个地方::tostring,但不知道如何调用TallProduct::toString,而不是SimpleProduct::toString.

标签: c++

解决方案


问题的另一半是:因为TallProduct没有初始化SimpleProduct所有类变量SimpleProduct都具有默认值。

char look = 'x';
string name = "Undefined";
string type = "Undefined";
string description = "Undefined";

因此ASSERT_EQ宏的参数不相等


推荐阅读