C ++ - 是否需要覆盖返回类型的指针 - 继承?

时间:2014-07-01 17:48:08

标签: c++ inheritance return-type

如果我有一个基类Attribute,它有一个名为clone的方法,它返回一个Attribute,但是当它的子类Direction收到错误时返回Direction

Attribute Attribute::clone() {
    if(this->currentValue) {
        return Attribute(this->type, this->currentValue);
    } else if (!this->param.empty()) {
        return Attribute(this->type, this->param);
    } else {
        return Attribute();
    }
}

Direction Direction::clone() {
    if(this->currentValue) {
        return Direction(this->type, this->currentValue);
    } else if (!this->param.empty()) {
        return Direction(this->type, this->param);
    } else {
        return Direction();
    }
}

尽管如此,它们都会返回指向新Attribtue的指针。 (即return new Attribtue();return new Direction();)。返回的值是否必须是指向Attribtue

的指针

编辑:以下是课程:

class Attribute {

public:
std::string param;
std::string type;
float currentValue;

Attribute(std::string type = "absolute", float value = 0);
Attribute(std::string type, std::string param);
~Attribute();
virtual Attribute clone();
};

class Direction : public Attribute{
public:
Direction(std::string type = "absolute", float value = 0);
Direction(std::string type, std::string param);
~Direction();
Direction clone();
};

1 个答案:

答案 0 :(得分:3)

C ++支持原始指针和原始引用的协变函数结果,但不支持其他类型。

这包括智能指针不支持协变结果。

然而,您可以轻松解决智能指针的语言限制,例如

class Base
{
private:
    virtual
    auto virtual_clone() const
        -> Base* 
    { return new Base( *this ); }

public:
    auto clone() const
        -> std::unique_ptr<Base>
    { return std::unique_ptr<Base>( virtual_clone() ); }
};

class Derived
    : public Base
{
private:
    auto virtual_clone() const
        -> Derived*                // Covariant is OK here. 
        override
    { return new Derived( *this ); }

public:
    auto clone() const
        -> std::unique_ptr<Derived>
    { return std::unique_ptr<Derived>( virtual_clone() ); }
};

免责声明:编译器未触及的代码。

请注意,在智能指针unique_ptr<Derived>的情况下,不是 unique_ptr<Base>的派生类,但会为后者提供值转换。


所以,关于问题标题,

  

是否需要覆盖返回类型的指针 - 继承?

基本答案是否定的,您可以使用非指针(例如智能指针实例)使其工作,但对于概念上类似于指针的内容,它只是有意义的

只是重复这个答案的开头句子,在语言层面C ++支持原始指针和原始引用的协变函数结果,但不支持其他类型。