c++ - 为什么这个转换为虚函数中的基类会出现段错误?

标签 c++ operator-overloading virtual segmentation-fault casting

我想使用 operator<< 打印出派生类.当我打印派生类时,我想先打印它的基类,然后再打印它自己的内容。

但是我遇到了一些麻烦(见下面的段错误):

class Base {
 public:
  friend std::ostream& operator<<(std::ostream&, const Base&);
  virtual void Print(std::ostream& out) const {
    out << "BASE!";
  }
};
std::ostream& operator<<(std::ostream& out, const Base& b) {
  b.Print(out);
  return out;
}

class Derived : public Base {
 public:
  virtual void Print(std::ostream& out) const {
    out << "My base: ";
    //((const Base*)this)->Print(out); // infinite, calls this fct recursively
    //((Base*)this)->Print(out);       // segfault (from infinite loop?)                                                          
    ((Base)*this).Print(out);          // OK
    out << " ... and myself.";
  }
};

int main(int argc, char** argv){
    Derived d;
    std::cout << d;
    return 0;
}

为什么我不能以其中一种方式转换?

    ((const Base*)this)->Print(out); // infinite, calls this fct recursively
    ((Base*)this)->Print(out);       // segfault (from infinite loop?)

最佳答案

尝试 Base::Print(out)

关于c++ - 为什么这个转换为虚函数中的基类会出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2657082/

相关文章:

C++ 链接时对基类函数的 undefined reference (--不是--vtables、构造函数、模板或纯虚函数)

C++ : error: invalid operands of types ‘String*’ and ‘const char [7]’ to binary ‘operator+’

c++ - 重写派生类中的某些重载,但不重写其他重载

c++ - 在 C++ 中查找紧密成员函数名称

c++ - 为什么 'allocate in one library and free in the other'是错误的

c# - 当 ==、CompareTo() 和 Equals() 不一致时会发生什么?

c++ - 无法对匿名对象使用运算符<<

c++ - 什么时候应该在 C++ 中使用 'friend'?

c++ - InstallShield 先决条件(错误 -7067)

c++ - 使用 stringstream 打印四舍五入的 float