C++[错误]
使用Markdown记录错误
错误名称:no match for ‘operator<<’ (operand types are ‘std::basic_ostream’ and ‘void’)
插入代码片
博客设置’ 代码片`.
#include<iostream>
using namespace std;
#include<string.h>
class SClass {
char *p;
public:
SClass(char *pn) {
p=new char[strlen(pn)+1];
strcpy(p,pn);
}
~SClass() {
delete p;
}
SClass &operator = (SClass &s){
delete p;
p=new char[strlen(s.p)+1];
strcpy(p,s.p);
return *this;
}
void disp() {
cout<<p<<endl;
}
};
int main(){
SClass s1("first object");
SClass s2("second object");
cout<<"S1="<<s1.disp()<<endl;
cout<<"S2="<<s2.disp()<<endl;
cout<<"复制之后:"<<endl;
s2=s1;
cout<<"S1="<<s1.disp()<<endl;
cout<<"S2="<<s2.disp()<<endl;
}
总结:
类的成员函数不能直接在cout输出,而应该分成两步走
正确代码如下:
#include<iostream>
using namespace std;
#include<string.h>
class SClass {
char *p;
public:
SClass(char *pn) {
p=new char[strlen(pn)+1];
strcpy(p,pn);
}
~SClass() {
delete p;
}
SClass &operator = (SClass &s){
delete p;
p=new char[strlen(s.p)+1];
strcpy(p,s.p);
return *this;
}
void disp() {
cout<<p<<endl;
}
};
int main(){
SClass s1("first object");
SClass s2("second object");
cout<<"S1="<<endl;
s1.disp();
cout<<"S2="<<endl;
s2.disp();
cout<<"复制之后:"<<endl;
s2=s1;
cout<<"S1="<<endl;
s1.disp();
cout<<"S2="<<endl;
s2.disp();
}