运算符重载 - C++ flush() 不起作用?无法使用 endl

operator overloading - C++ flush() not working? Can't use endl

本文关键字:endl 不起作用 重载 C++ flush 运算符      更新时间:2023-10-16

对于类赋值,我必须重载插入和提取操作符。我把它打印到控制台有问题。

对不起,这是我第一次发帖。我意识到我没有为你们发布足够的信息,我已经更新了应该是必要的代码

driver.cpp

#include "mystring.h"
#include <iostream>
using namespace std;
int main(){
    char c[6] = {'H', 'E', 'L', 'L', 'O'}
    MyString m(c);
    cout << m;
    return 0;
}

mystring.h

class MyString
{
  friend ostream& operator<<(ostream&, const MyString&);
  public:
    MyString(const char*);
    ~MyString(const MyString&)
  private:
    char * str;  //pointer to dynamic array of characters
    int length;  //Size of the string
  };

mystring.cpp

#include "mystring.h"
#include <iostream>
#include <cstring>
using namespace std;
MyString::MyString(const char* passedIn){
    length = strlen(passedIn)-1;
    str = new char[length+1];
    strcpy(str, passedIn);
}
MyString::~MyString(){
  if(str != NULL){
    delete [] str;
  }
}
ostream& operator << (ostream& o, const MyString& m){
  for(int i = 0; i < strlen(m.str); i++){
    o << m.str[i];
  }
  o.flush();
  return o;
}

使用ostream::flush()方法。如:

ostream& operator << (ostream& o, const MyString& m){
    for(int i = 0; i < strlen(m.str)-1; i++){
        o << m.str[i];
    }
    o.flush();
    return o;
}

不要尝试从插入器内部清除。标准的插入器都不会这样做。只需在main中的插入器调用后添加std::cout << 'n';即可。

这里的问题是std::cout是行缓冲的。这意味着它将插入的字符保存在内部缓冲区中,直到它看到换行符(或者直到显式刷新)。如果您插入std::string对象,但不结束行,您将看到相同的行为。