C++ C++;-重写返回类型-继承是否需要指针?

C++ C++;-重写返回类型-继承是否需要指针?,c++,inheritance,return-type,C++,Inheritance,Return Type,如果我有一个基类,Attribute,它有一个名为clone的方法,该方法返回一个属性,但它的子类方向在返回方向时出错 Attribute Attribute::clone() { if(this->currentValue) { return Attribute(this->type, this->currentValue); } else if (!this->param.empty()) { return Attrib

如果我有一个基类,
Attribute
,它有一个名为
clone
的方法,该方法返回一个
属性
,但它的子类
方向
在返回
方向时出错

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();
    }
}

尽管如此,当它们都返回指向新的
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();
};

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() ); }
};
类基
{
私人:
事实上的
自动虚拟克隆()常量
->基地*
{返回新基(*this);}
公众:
自动克隆()常量
->std::unique\u ptr
{return std::unique_ptr(virtual_clone());}
};
类派生
:公共基地
{
私人:
自动虚拟克隆()常量
->派生的*//协变在这里是可以的。
推翻
{返回新的派生(*this);}
公众:
自动克隆()常量
->std::unique\u ptr
{return std::unique_ptr(virtual_clone());}
};
免责声明:编译器的手不能触摸代码

请注意,在这种情况下,智能指针
unique_ptr
不是
unique_ptr
的派生类,而是提供到后者的值转换


那么关于题目,

重写返回类型-继承是否需要指针

基本的答案是否定的,您可以使非指针也能工作,例如智能指针实例,但它只对概念上类似指针的东西有意义


<> P>并重复这个答案的开头句,在语言层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() ); }
};