C++程序帮忙看下哪错

来源:百度知道 编辑:UC知道 时间:2024/05/28 04:57:42
#include<iostream.h>
class point
{
public:
void show();
void get();
private:
char *b;
static int a;
// int n=0;
};
char *b=new char;
int point::a=0;
void point::get()
{
cout<<"输入字符串"<<endl;
cin>>b;
a++;

}
void point::show()
{int n=0;
while(*b!='/0')
{n++;
*b++;}
cout<<"对象"<<a;
cout<<"字符个数"<<n;
}
main()
{
point a1;
a1.get();
a1.show();
point a2;
a2.get();
a2.show();

}
给我修改后的答案就可以了,要运行正确的,使用指针

#include<iostream.h>
class point
{
public:
void show();
void get();
private:
char *b;
static int a;
// int n=0;
};
//char *b=new char;修改1,此处b为一全局变量,非class point里的b
int point::a=0;
void point::get()
{
b=new char;
cout<<"输入字符串"<<endl;
cin>>b;
a++;

}
void point::show()
{int n=0;
while(*b!='\0')//修改2
{n++;
*b++;}
cout<<"对象"<<a;
cout<<"字符个数"<<n;
}
main()
{
point a1;
a1.get();
a1.show();
point a2;
a2.get();
a2.show();

}

楼上的做法会造成内存的泄漏,因为new里面只是申请了一个地址空间,而输入的字符串需要多个地址空间,造成失控,无法回收,所以建议把b=new char改为b=new char[20],最后调用析构函数回收内存。

#include<iostream.h>
class point
{
public:
void show();
void get();
~point();
private:
char *b;
char *c;
static