【问题标题】:Operator() overlading and inheritance in C++ errorC++ 错误中的运算符()重载和继承
【发布时间】:2013-03-20 18:24:23
【问题描述】:

这是我的问题:

代码:

file1.hpp:

namespace Output {

class Stringify{ // base class.....
protected:
    size_t              prec;
public:
    std::stringstream   out;
public:
    Stringify(const size_t& _p = 5): prec(_p) {out.precision(prec);}
    virtual ~Stringify(void){}
public:
    std::string operator()(const XYZ& _v){
        out.str("");
        out << "{ " << _v.x() << ", " << _v.y() << ", " << _v.z() << " }";
        return out.str();
    }
    std::string operator()(const XYZ& _v, const bool& _status){
        out << "{ " << _v.x() << ", " << _v.y() << ", " << _v.z() << " }";
        return out.str();
    }
};
}

其中 XYZ 是一个矢量对象。

file2.hpp:

namespace NODE { 

class Stringify: public Output::Stringify {
public:
    Stringify2(const size_t& _p = 5): Output::Stringify(_p) {}
    virtual ~Stringify2(void){}
public:
    std::string operator()(const VERTEX& _obj){ return "What?";}
};
}

其中 VERTEX 是另一个具有 XYZ 类型成员值的对象

main.cpp:

int main(int argc,char * argv[]){
   XYZ  v(1,2,3);
   NODE::Stringify printer;

   cout << printer(v) << endl;
   return 0;

}

输出是: 什么?

什么时候应该: 是{1,2,3}

编译没问题,但是, 据我所知,NODE::Stringify 能够打印 {1,2,3},因为他的基础对象 继承了 XYZ 参数的方法,但它使用参数打印方法 顶点(什么?)。虚拟词不是必需的,因为我没有覆盖其中的方法 基类。

作为信息:我正在使用 llvm-gcc-4.2 在 MAC OS 10.8 中编译 使用 Eigen 3.0 库(typedef Eigen::vector3d XYZ) 有什么想法吗?

提前致谢。

【问题讨论】:

    标签: c++ inheritance operator-overloading operator-keyword


    【解决方案1】:

    您在派生类中的operator ()隐藏基类中的operator () 重载(在您的示例中您将其命名为Stringify,但这可能是一个错字,因为构造函数和析构函数被命名为(~)Stringify2)。

    您可以通过派生类中的using 声明来解决此问题:

    namespace NODE {
        class Stringify2 : public Output::Stringify {
        //             ^
        public:
            using Output::Stringify::operator ();
        //  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        //  This should fix the problem
    
            Stringify2(const size_t& _p = 5): Output::Stringify(_p) {}
            virtual ~Stringify2(void){}
        public:
            std::string operator()(const VERTEX& _obj){ return "What?";}
        };
    }
    

    【讨论】:

    • 值得注意的是,这只有在XYZ类型与VERTEX类型兼容的情况下才有可能,否则会出现编译错误。
    • @icepack:确实。正如 OP 所提到的,VERTEX 有一个XYZ 类型的成员,所以我相信它也有一个非explicit 构造函数接受一个XYZ 来初始化它的成员,这就是他没有编译器的原因错误
    猜你喜欢
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多