【发布时间】:2016-07-05 20:13:58
【问题描述】:
对于类分配,我必须重载插入和提取运算符。我无法将其打印到控制台。
已编辑
对不起,这是我第一次发帖。我意识到我没有为你们发布足够的信息,我已经更新了应该是必要的代码
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;
}
【问题讨论】:
-
我建议要么发布相关的
MyString代码,要么创建一个不需要MyString的minimal reproducible example。 -
感觉是因为你缺少空字符
-
此外,如果
m.str是 C 风格的字符串,则此代码将删除其最后一个字符。显示的代码存在多个问题。 -
我已经更新了我的帖子,以包含更多相关/有用的信息,并希望制作一个最小、完整和可验证的示例。
-
strlen(passedIn)这是未定义的行为,因为它不是以空值终止的。
标签: c++ operator-overloading flush