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

求大神帮小弟我看一下这个代码哪里有有关问题

2013-11-09 
求大神帮我看一下这个代码哪里有问题我是新手,编了一个简单程序,不出结果,求大神帮我看一下哪里出了问题!!

求大神帮我看一下这个代码哪里有问题
我是新手,编了一个简单程序,不出结果,求大神帮我看一下哪里出了问题!!!

# include<iostream.h>
# include<string.h>
class tc
{
public:
tc(){num=0;}
tc(char *p);
~tc();
void count();
private:
char *x;
int num;
};
tc::tc(char *p)
{
x=new char[strlen(p)+1];
strcpy(x,p);
}
tc::~tc()
{
delete[] x;
}
void tc::count()
{
while(x[num]!='\0')
{
num++;
}
cout<<"the length of the sentence is:"<<num<<endl;
}
void main()
{
tc s("good morning!");
s.count();
} c++??类与对象??while循环
[解决办法]
是因为你的num没有初始化,这里调用的是有参构造函数!num没有初始化,访问数据可能越界
帮你修改了程序,看看


# include<iostream>
# include<string.h>
using namespace std;
class tc
{
public:
tc(){num=0;} 
tc(char *p);
~tc();
void count();
private:
char *x;
int num;
};
tc::tc(char *p)
{
x =NULL;
num = 0;
x=new char[strlen(p)+1];
strcpy(x,p);
}
tc::~tc()
{
if( x != NULL )
delete[] x;
}
void tc::count()
{
while(x[num]!='\0')
{
num++;
}
cout<<"the length of the sentence is:"<<num<<endl;
}

int main()
{
tc s("good morning!");
s.count();
return 0;
}

[解决办法]
感觉这样写会好一些:

# include<iostream>
# include<string.h>
using namespace std;
class tc
{
public:
tc():x(NULL),num(0){}
tc(const char *p);
~tc();
void count();
private:
char *x;
int num;
};
tc::tc(const char *p)
{
num = strlen(p);
x=new char[num+1];
strcpy(x,p);
}
tc::~tc()
{
if( x != NULL)
delete[] x;
}
void tc::count()
{
cout<<"the length of the sentence is:"<<num<<endl;
}

int main()
{
tc s("good morning!");
s.count();
return 0;
}

热点排行