C++ 帮忙看看是那里出错
我自己做 的一个练习题: 下面是源代码:
# include "Cyuyan.h "
class string2
{
char buffer[50];
public:
string2();
string2(char *buff);
string2(string2 & obj);
string2 & operator = (const string2 & object);
~string2();
void m_set();
void m_display();
void m_strlen();
};
string2::string2() //无参构造函数
{
char str[] = "\0 ";
strcpy(buffer, str);
};
string2::string2(char *buff) //构造函数
{
strcpy(buffer, buff);
};
string2::string2(string2 &obj) //复制构造函数
{
strcpy(buffer, obj.buffer);
};
string2 & string2::operator =(const string2 & object) //对象连接函数
{
strcat(buffer, object.buffer);
return * this;
}
string2::~string2() //析构函数
{
//delete [] buffer; //delete 要和 new 配对使用
cout < < "析构函数释放空间! " < < endl;
};
void string2::m_set() //对象设置函数
{
char str1[50];
cout < < "对象值设置,请输入一个字符串: " ;
cin.getline(str1,50, '\n '); //getline 函数可以自动提取空格
strcpy(buffer,str1);
};
void string2::m_display() //显示对象字串
{
cout < < "对象的值为: ";
cout < < buffer;
cout < < endl;
}
void string2::m_strlen() //求对象字串长
{
int temp = 0;
for(temp=0; buffer[temp] != '\0 ';temp++);
cout < < temp < < endl;
};
int main(void)
{
string2 str1;
cout < < "object str1 初始化值为: ";
str1.m_display();
char st[] = "I love you more than the star above! ";
string2 str2(st);
cout < < "object str2 初始化值为: ";
str2.m_display();
string2 str3;
cout < < "新建一个对象str3. " < < endl;
str3.m_set();
cout < < endl;
cout < < "对象str3设置后对象的新值为: " < < endl;
str3.m_display();
string2 str4(str3);
cout < < "复制str3给str4后,object str4 的值为: " < < endl;
str4.m_display();
cout < < "object str1的值为 : " < < endl;
str1.m_display();
cout < < "object str2的值为 : " < < endl;
str2.m_display();
str4 = str2;
cout < < "object str4 连接str2 后,object str4的值为: " < < endl;
str4.m_display();
cout < < "object str2的值为 : " < < endl;
str2.m_display();
cout < < "object str1~4 的长度分别为 : " < < endl;
str1.m_strlen();
str2.m_strlen();
str3.m_strlen();
str4.m_strlen();
cout < < "press any key continue...... " < < endl;
getch();
return 0;
}
本来运行后object str1的长度是0,但是结果是12,还不会调试 ,希望高手帮忙看看是出在那里 ,要分析结果。。
下面是运行后的 结果:
object str1 初始化值为:对象的值为:
object str2 初始化值为:对象的值为:I love you more than the star above!
新建一个对象str3.
对象值设置,请输入一个字符串:you are the apple of my eye!
对象str3设置后对象的新值为:
对象的值为:you are the apple of my eye!
复制str3给str4后,object str4 的值为:
对象的值为:you are the apple of my eye!
object str1的值为 :
对象的值为:
object str2的值为 :
对象的值为:I love you more than the star above!
object str4 连接str2 后,object str4的值为:
对象的值为:you are the apple of my eye!I love you more than the star above!
object str2的值为 :
对象的值为:I love you more than the star above!
object str1~4 的长度分别为 :
12
36
28
64
press any key continue......
[解决办法]
应该不是楼主说的那样,出错的应该是str3;str1没有错
我用VC6.0和Devcpp编译运行结果是这样的:
///////////////////////VC6.0:
object str1~4 的长度分别为 :
0
36
12 //////////!!!!!
64
//////////////////////////Devcpp:
object str1~4 的长度分别为 :
0
36
0 //////////!!!!
64
应该是楼主定义buffer[50]但在使用时str4产生溢出而导致的“不可预期”结果,呵呵。如果把buffer定义为buffer[65],则对此问题,一切OK;个人感觉把buffer定义成vector类型比较好。