C++改错题,下面这个程序哪里出错了?应该怎么改?

来源:百度知道 编辑:UC知道 时间:2024/06/21 18:51:28
#include<iostream.h>
#include<string.h>
class CBase{
protected:
char *ch;
public:
CBase(char *x)
{
ch=new char[20];
strcpy(ch,x);
}
virtual void fun()=0;
virtual void fun1()
{cout<<x<<endl;};
~CBase()
{delete []ch;cout<<"~CBase()"<<endl;}
};
class CDerived:CBase{
protected:
char *ch;
public:
CDerived(char *x,char *y):CBase(y)
{
ch=new char[20];
strcpy(ch,x);
}
void fun1()
{cout<<x<<endl;}
~CDerived()
{delete []ch;cout<<"~CDerived()<<endl;";}
};
void main()
{
CBase obj1("Hello"),*p;
p=&obj1;
p->fun1();
p->fun();
p=new CDerived("China","Hello");
p->fun1();
p->fun();
delete p;
}
应该改成怎么样才正确?

CBase中含有virtual void fun()=0; 是抽象类,是不能创建对象的。

你的头文件写法不规范,在新的c++标准中是错误的。
main函数写法也是错误的。
并且基类和派生类都应该定义拷贝构造函数,而你没有定义。
另外注意不要把const char* 隐转换为char*

修改后的代码:

#include<iostream>
#include<string>
#include <cstring>
using namespace std;
class CBase
{

protected:
char *ch;

public:
CBase(const char *x)
{
ch = new char[20];
strcpy(ch, x);
}

virtual void fun() {};
virtual void fun1()
{
cout << ch << endl;
};

~CBase()
{
delete []ch;
cout << "~CBase()" << endl;
}
};

class CDerived: public CBase
{

protected:
char *ch;

public:
CDerived(const char *x, const char *y): CBase(y)
{
ch = new char[20];
strcpy(ch, x);
}

void fun1()
{
cout <<