c++ - 如何正确重载从基类到继承的转换

标签 c++ inheritance type-conversion operator-overloading overloading

我觉得我的问题简单明了:

我有基类 AbstractMatrix 和它的子类 Matrix,我想做简单的转换:

namespace mtrx {
/* mycode */
    class AbstractMatrix {
        public:
        /* -//- */
        operator Matrix ();
        /* -//- */
    }
    class Matrix : public AbstractMatrix {
    /* -//- */
    }
}

抽象矩阵.cpp:

AbstractMatrix::operator Matrix(){
    return Matrix(data);
}

编译器给出信息:

Matrix.h:39:12: error: expected type-specifier before ‘Matrix’
   operator Matrix ();
            ^

我做错了什么? 是否可以进行此类转换?我想是的,因为我只想基于父类(super class)创建构造函数,但没有任何无聊的语法,我需要它隐式

谢谢

最佳答案

您应该简单地提供一个前向声明:

namespace mtrx {

    class Matrix; // <=== here

    class AbstractMatrix {
        public:
        operator Matrix ();
    };

    class Matrix : public AbstractMatrix {

    };

}

使 MatrixAbstractMatrix 类可见。


附言您可能应该重新考虑您的设计,因为使用转换运算符将基类转换为派生类对我来说很奇怪。

关于c++ - 如何正确重载从基类到继承的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45016326/

相关文章:

c++ - "Template argument for template template parameter must be a class template or type alias template"

c++ - 使用 MinGW 静态链接到 Windows 上的 libarchive

c++ - Qt Object::connect: 没有这样的插槽信号到线程插槽

python - 用不同的 __new__ 签名为 child 实例化 __new__ 中的 child

java - 如何在 Java-Selenium 中将 String "rgba(105, 54, 221, 1)"类型的对象转换为 Color?

c++ - 如果一个char是一个空格,用C++中的 '+'替换它

c++ - 函数调用继承 C++

C++ 模板子类和多重继承歧义

c++ - 如何在C++中将整数转换为字符

c++ - 如何从单个字符创建字符串?