求教啊,operator<<的操作符重载
#include<iostream>
using namespace std;
class MyString{
public:
MyString(char*s){
str=new char[strlen(s)+1];
strcpy(str,s);
}
~MyString(){
delete[]str;
}
ostream&operator<<(ostream&os,MyString&string){
str=new char[strlen(string.str)+1];
strcpy(str,string.str);
return os<<str<<endl;
}
private:
char*str;
};
int main(){
MyString a("hello");
cout<<a<<endl;
return 0;
}
操作符重载出错啊,求指教啊
[解决办法]
- C/C++ code
#include<iostream> using namespace std; class MyString{ public: MyString(char*s){ str=new char[strlen(s)+1]; strcpy(str,s); } ~MyString(){ delete[]str; }//注意 friendfriend ostream&operator<<(ostream&os,MyString&string){ str=new char[strlen(string.str)+1]; strcpy(str,string.str); return os<<str<<endl; } private: char*str; }; int main(){ MyString a("hello"); cout<<a<<endl; return 0;}
[解决办法]
重载>>和<<只能设为非成员函数!!- C/C++ code
#include<iostream> using namespace std; class MyString{ public: MyString(char*s){ str=new char[strlen(s)+1]; strcpy(str,s); } ~MyString(){ delete[]str; }//注意 friendfriend ostream&operator<<(ostream&os,MyString&string); private: char*str; }; ostream&operator<<(ostream&os,MyString&string){ str=new char[strlen(string.str)+1]; strcpy(str,string.str); return os<<str<<endl; } int main(){ MyString a("hello"); cout<<a<<endl; return 0;}