运算符重载 - C++ flush() 不起作用?无法使用 endl
operator overloading - C++ flush() not working? Can't use endl
对于类赋值,我必须重载插入和提取操作符。我把它打印到控制台有问题。
对不起,这是我第一次发帖。我意识到我没有为你们发布足够的信息,我已经更新了应该是必要的代码
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
对象,但不结束行,您将看到相同的行为。
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++为什么尽管我调用了void函数,它却不起作用
- 为什么在保护模式下继承升级不起作用
- 循环在计数器中不起作用
- 在其他文件中创建类时在 c++ 项目中不起作用
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 为什么二进制搜索在我的测试中不起作用
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 带有指定长度字符* 参数的 std::regex_search 在 VS2017 中不起作用?
- Bjarne Stroustrup Book - std_lib_facilities.h - 不起作用(未知类型名称)
- 为什么简单的算术减法在"if"条件下不起作用?
- 为什么Stroustup书中的has_f不起作用
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 嵌套While循环不起作用(C++问题)
- C++Matching Brackets 2解决方案不起作用
- std::flush 不起作用,而 std::endl 可以
- 运算符重载 - C++ flush() 不起作用?无法使用 endl