C ++ flush()不起作用?无法使用endl

时间:2016-07-05 20:13:58

标签: c++ operator-overloading flush

对于类赋值,我必须重载插入和提取操作符。我无法将其打印到控制台。

EDITED

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

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;
}

2 个答案:

答案 0 :(得分:1)

使用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;
}

答案 1 :(得分:1)

请勿尝试从插入器内部冲洗。没有标准的插入器能做到这一点。只需在std::cout << '\n';调用插件后添加main

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