首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

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

2012-04-04 
string类对象的赋值------------------------------string.cpp#includeiostream.h#includestring.hcla

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导入进来,以便程序使用

热点排行