读书人

string类对象的赋值,该如何处理

发布时间: 2012-04-04 16:38:51 作者: rapoo

string类对象的赋值
------------------------------string.cpp
#include<iostream.h>
#include<string.h>
class string{
char *str;
public:
string(char *s=" ")
{str=new char[strlen(s)+1];strcpy(str,s);}
~string(){delete str;}
void print()
{
cout<<str<<endl;
}
string & operator=(const string & s)
{
if(this==&s)
return *this;
delete str;
str=new char[strlen(s.str)+1];
strcpy(str,s.str);
return *this;
}
};
void main()
{
string s1("abcd");
{
string s2(" ");
s2=s1;
cout<<"s2:"<<s2.print();
}
cout<<"s1:"<<s1.print();
}
有错误
--------------------Configuration: Cpp1 - Win32 Debug--------------------
Compiling...
Cpp1.cpp
error C2679: binary '<<' : no operator defined which takes a right-hand operand of type 'void' (or there is no acceptable conversion)

error C2679: binary '<<' : no operator defined which takes a right-hand operand of type 'void' (or there is no acceptable conversion)
Error executing cl.exe.

Cpp1.exe - 2 error(s), 0 warning(s)
请高手帮忙


[解决办法]
#include <iostream>
using std::cout;
using std::endl;
class string{
char *str;
public:
string(char *s=" ")
{str=new char[strlen(s)+1];strcpy(str,s);}
~string(){delete str;}

void print()
{
cout<<str<<endl;
}

string & operator=(const string & s)
{
if(this==&s)
return *this;
delete str;
str=new char[strlen(s.str)+1];
strcpy(str,s.str);
return *this;
}
};

int main()
{
string s1("abcd");
{
string s2(" ");
s2=s1;
s2.print();
}
s1.print();
getchar();
}
[解决办法]
using std::cout;
using std::endl;
这个是使用声明,将std名字空间中的cout和endl导入进来,以便程序使用

读书人网 >C++

热点推荐