超级简单的问题。。。非常感谢。。。如果你帮忙看看。。。。。

TemplatesGuy 2005-03-27 04:51:22
#include <iostream>
#include <cstring>
using namespace std;

class StringBad
{
private:
int len;
char *str;
static int num_strings;
public:
StringBad(const char *s);
StringBad();
~StringBad();
friend ostream & operator << (ostream &os,const StringBad &st);
};
int StringBad::num_strings=0;
StringBad::StringBad(const char *s)
{
len=strlen(str);
s=new char[len+1];
strcpy(str,s);
num_strings++;
cout<<num_strings<<" \" "<<str <<" \" object created!";
}
StringBad::StringBad()
{
len=4;
str=new char[4];
strcpy(str,"C++");
num_strings++;
cout<<num_strings<<" \" "<<str<<" \" object created!";
}
StringBad::~StringBad()
{
cout<<"\" " <<str<<" \" object deleted!";
--num_strings;
cout<<num_strings<<" left \n";
delete [] str;
}

ostream &operator<<(ostream &os,const StringBad &st)
{
os<<st.str;
return os;
}


//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
void callme1(StringBad &);
void callme2(StringBad);
int main()
{
StringBad headline1("Celery Stalks at Midnight");
StringBad headline2("Lettuce Prey");
StringBad sports("Spinach Levaes Bow1 for Dollars");
cout<<"headline1: " << headline1 <<endl;
cout<<"headline2: " << headline2 <<endl;
cout<<"sports:"<<sports<<endl;
callme1(headline1);
cout<<"headline1: " <<headline1<<endl;
callme2(headline2);
cout<<"headline2: " <<headline2<<endl;

cout<<"初始化另一个对象:\n";
StringBad sailor=sports;
cout<<"sailor:" <<sailor<<endl;
cout<<"Assign one object to another: \n";
StringBad knot;
knot=headline1;
cout<<"knot:" <<knot<<endl;
cout<<"Enf of main() \n";

return 0;
}
void callme1(StringBad &s)
{
cout << "String passed by reference : \n";
cout << " \"" <<s <<" \" \n";
}
void callme2(StringBad sb)
{
cout<<"String passed by value : \n";
cout <<" \" "<<sb<<" \" \n";
}

======================================================

以上代码用7.1 CL编译通过。但会出现异常。。。
请帮忙看看。

...全文
72 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
薛定谔之死猫 2005-03-27
  • 打赏
  • 举报
回复
如vcmute所说,不好意思,我没有说清楚
TemplatesGuy 2005-03-27
  • 打赏
  • 举报
回复
@
mscf


这是一个简单的字符串类,,

有缺陷我知道,再至少是可以运行的呀。。

-===============
能不能具体说说哪里错了?

谢谢大虾
vcmute 2005-03-27
  • 打赏
  • 举报
回复
StringBad::StringBad(const char *s)
{
len=strlen(s);
str=new char[len+1];
strcpy(str,s);
num_strings++;
cout<<num_strings<<" \" "<<str <<" \" object created!";
}
薛定谔之死猫 2005-03-27
  • 打赏
  • 举报
回复
不知道你的类什么用意,有点混乱
问题出在用于存储字符串的空间没有开够,应该说直接没有开,肯定会出现访问违例

16,472

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC相关问题讨论
社区管理员
  • 基础类社区
  • Web++
  • encoderlee
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

        VC/MFC社区版块或许是CSDN最“古老”的版块了,记忆之中,与CSDN的年龄几乎差不多。随着时间的推移,MFC技术渐渐的偏离了开发主流,若干年之后的今天,当我们面对着微软的这个经典之笔,内心充满着敬意,那些曾经的记忆,可以说代表着二十年前曾经的辉煌……
        向经典致敬,或许是老一代程序员内心里面难以释怀的感受。互联网大行其道的今天,我们期待着MFC技术能够恢复其曾经的辉煌,或许这个期待会永远成为一种“梦想”,或许一切皆有可能……
        我们希望这个版块可以很好的适配Web时代,期待更好的互联网技术能够使得MFC技术框架得以重现活力,……

试试用AI创作助手写篇文章吧