對於類分配,我必須重載插入和提取操作符。我無法將其打印到控制檯。C++ flush()不工作?不能使用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;
}
我建議發佈相關的'MyString'代碼,或者製作一個不需要'MyString'的[mcve]。 – juanchopanza
感覺這是因爲你缺少空字符 –
此外,如果'm.str'是一個C風格的字符串,這段代碼將刪除它的最後一個字符。顯示的代碼有多個問題。 –