为什么我的输出流seg出错,而我的虚拟析构函数不起作用,但当我杀死虚拟的时候,它起作用了

Why is my output stream seg faulting and my virtual destructor does not work but when i kill virtual it does

本文关键字:虚拟 我的 起作用 出错 seg 输出流 析构函数 为什么 不起作用      更新时间:2023-10-16

我正在复习测试,我正在进行我的个人项目,但我正在进行增量开发。我想在大学里取得好成绩。

它在我的ostream操作符上设置了错误,我的虚拟函数不起作用,除非它有out virtual。

    #include"MyString.h"


 MyString::MyString( )  //constructor
 {
     size=0;
     capacity=1;
     data=new char[capacity];
 }
  MyString::MyString(char * n)  //copy constructor
 {
     size=strlen(n);
     capacity=strlen(n)+1;
   data=new char[capacity];
   strcpy(data,n);
 }
  MyString::MyString(const MyString &right)  //
 {
     size=strlen(right.data);
     capacity=strlen(right.data)+1;
   data=new char [capacity];
   strcpy(data,right.data);
 }
   MyString::~MyString( )
 {
  delete [] data;
 }
 MyString  MyString::operator = (const MyString& s)
 {
     if(this!=&s)
{
    MyString temp=data;
    delete [] data;
    size=strlen(s.data);
    capacity=size+1;
    data= new char [capacity];
    strcpy(data,s.data);
}
 }
 MyString&  MyString::append(const MyString& s)
 {
    if(this!=&s)
    {
        strcat(data,s.data);
    }

 }
 MyString&  MyString::erase()
 {
 }
 MyString  MyString::operator + (const MyString&)const
 {
 }
 bool  MyString::operator == (const MyString&)
 {
 }
 bool  MyString::operator <  (const MyString&)
 {
 }
 bool  MyString::operator >  (const MyString&)
 {
 }
 bool  MyString::operator <= (const MyString&)
 {
 }
 bool  MyString::operator >= (const MyString&)
 {
 }
 bool  MyString::operator != (const MyString&)
 {
 }
 void  MyString::operator += (const MyString&)
 {
 }
 char&  MyString::operator [ ] (int)
 {
 }
 void  MyString::getline(istream&)
 {
 }
 int  MyString::length( ) const
 {
     return strlen(data);
 }

ostream& operator<<(ostream& out, MyString& s){
 out<<s;
 return out;

}

// int  MyString::getCapacity(){return capacity;}
实现的operator<<()是一个无限递归调用:
ostream& operator<<(ostream& out, MyString& s){
    out<<s;
    return out;
}

并且将导致堆栈溢出。

我想你的意思是:

ostream& operator<<(ostream& out, MyString& s){
    out << s.data;
    return out;
}

虽然不确定,但我认为这会更好地工作(我认为数据是一个以0结尾的c字符串)。

ostream& operator<<(ostream& out, MyString& s) {
    out<<s.data;
    return out;
}