无法使用在子类中定义的虚拟获取器实现基类

问题描述 投票:0回答:1

我有一个叫做Object的类,该类的头是:

class DLL_SPEC Object {
public:
    Object();
    virtual ~Object();

    virtual std::string getString() const;
    virtual void setString(std::string value);

    virtual int getInt() const;
    virtual void setInt(int value);

    virtual double getDouble() const;
    virtual void setDouble(double value);

    virtual bool isType(FieldType type) const;
};

我的孩子班级如下:

class DLL_SPEC IntObject : public Object {
public:
    IntObject() : value(0) {}
    IntObject(int v) : value(v) {}
    void setInt(int value) override { this->value = value; };
    int getInt() const override { return this->value; };
    bool isType(FieldType type) const override;
private:
    int value;
};

class DLL_SPEC DoubleObject : public Object {
public:
    DoubleObject() : value(0.0) {}
    DoubleObject(double v) : value(v) {}
    void setDouble(double value) override { this->value = value; };
    double getDouble() const override { return this->value; };
    bool isType(FieldType type) const override;

private:
    double value;
};
class DLL_SPEC StringObject : public Object {
public:
    StringObject() : value("") {}
    StringObject(std::string v) : value(v) {}
    void setString(std::string value) override { this->value = value; };
    std::string getString() const override { return value; };
    bool isType(FieldType type) const override;

private:
    std::string value;
};

现在,问题是,我有一个对象数组,我想获取StringObject的字符串表示形式。

我叫array[0].getString(),即使对象的类型为StringObject,但被调用的方法是基类,据我了解。

所以,每当我在基类上调用getString()时,它将去实现SAME对象之一的子对象?

我尝试使用此方法:

std::string Object::getString() const
{
    return dynamic_cast<StringObject*>(this).getString();
}

但是我得到一个错误,指出我不能抛弃const或任何类型限定符,这可以通过删除const修饰符来解决(根据任务,我必须将其保留在那儿),但是随后我得到另一个提示,指出不适合构造函数存在。因此,我将如何实现它并让该基类使用子类之一?

c++ inheritance base-class
1个回答
0
投票

问题很简单:您必须通过指针进行调用。

array[0].getString() 

应更改为:

(&(array[0]))->getString();

不是所有括号都需要,但有助于弄清正在发生的事情...

© www.soinside.com 2019 - 2024. All rights reserved.