关于c++中字符串串接的操作符重载问题

来源:百度知道 编辑:UC知道 时间:2024/05/17 20:52:15
已知类Cstring和main()函数
class Cstring{
char *str;
int size;
public:
….
};
主程序如下:
void main()
{
Cstring s1(“C++ is a wondful ”);//调用有字符串参数的构造函数
Cstring s2( “Language!”);
Cstring s3; //调用没有参数的构造函数
s3= s1+ “programming ”+s2 //调用复制(拷贝)构造函数,同时还要对“+”进行重载
}
下面是我编的程序(没有编完,因为不会重载这种字符串的 +):
#include<iostream.h>
#include<string.h>
class Cstring
{
char *str;
int size;
public:
Cstring(const char * s)
{
size =strlen(s); // set size
str = new char[size + 1]; // allot storage
strcpy(str, s); // initialize pointer
cout<<str;
}
Cstring()
{
size = 100;
str = new char[100];
}

friend Cstring operator +(Cstring s1,char t[15])
{
Cstring s3;
s3.str=s1.str+t[15];
return s3.str;

你的重载函数的函数体写错了串连不是简单的加,string.h有一个strcat(()函数专门用来连接的不可能还没有定义好+运算出类就用吧!
可可
会是你想要的

#include<iostream.h>
#include<string.h>
class Cstring
{
char *str;
int size;
public:
Cstring(const char * s)
{
size =strlen(s); // set size
str = new char[size + 1]; // allot storage
strcpy(str, s); // initialize pointer

}
Cstring()
{
size = 100;
str = new char[100];
}

friend Cstring operator +(Cstring s1,char t[15])
{

strcat(s1.str,t);
return s1;
}
friend Cstring operator +(Cstring s1,Cstring s2)
{

strcat(s1.str,s2.str);
return s1;
}
void dis()
{cout<<str;}
};
void main()
{
Cstring s1("C++ is a wondful ");//调用有字符串参数的构造函数
Cstring s2( "Language!");
Cstring s3;
Cstring s4; //调用没有参数的构造函数
s3= s1+ "progra