C++PrimerPlus:第十三章类和继承:编程练习
提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加
例如:完成练习1,但让这两个类使用动态内存分配而不是长度固定的数据来记录字符串
提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
完成练习1,但让这两个类使用动态内存分配而不是长度固定的数据来记录字符串
1,头文件的修改
只需要把数组声明修改为指针,比如
基类的修改
1,修改变量,
2,增加赋值运算符
3,增加重载构造函数
char performers[50] ;修改为
char* performers;
label 同样的道理
派生类的修改
char songs[size];//修改为
char* songs;
修改好的头文件
#ifndef PE13_1_H
#define PE13_1_H
//base class
class Cd
{
private:
char* performers;
char* label;
int selections;
double playtime;
public:
explicit Cd(const char* s1 = "", const char* s2 = "",
int n = 0, double x = 0);
Cd(const Cd& d);
virtual void Report() const;
virtual ~Cd() { delete[] performers;delete[]label; };
Cd& operator=(const Cd& d);
};
class Classic : public Cd
{
private:
//static const unsigned mk_size = 64;
char* m_songs;
public:
Classic(const char* s1 = "", const char* s2 = "",
const char* s3 = "", int n = 0, double x = 0);
Classic(const Classic& c);
virtual void Report() const;
virtual ~Classic();
Classic& operator=(const Classic& c);
};
#endif
2,方法的修改
方法的修改,这要正对数组变指针做的改动,同时增加操作符的处理
//pe13-1.cpp -- using the new and delete operators
#define _CRT_SECURE_NO_WARNINGS
#include "pe13-2.h"
#include <string.h>
#include <iostream>
#include <cstring>
static char*
cpStr(const char* p_src_txt)
{
unsigned str_len = strlen(p_src_txt);
char* p_dest_txt = new char[str_len + 1];
strcpy(p_dest_txt, p_src_txt);
return p_dest_txt;
}
Cd::Cd(const char* s1, const char* s2,
int n, double x) :selections(n), playtime(x)
{
performers = cpStr(s1);
label = cpStr(s2);
}
Cd::Cd(const Cd& d) :selections(d.selections), playtime(d.playtime)
{
performers = cpStr(d.performers);
label = cpStr(d.label);
}
void Cd::Report() const
{
std::cout << performers << ", " << label << ", " << selections << ", " << playtime << std::endl;
}
Cd& Cd::operator=(const Cd& d)
{
if (this == &d)
return *this;
delete[] performers;
delete[] label;
performers = cpStr(d.performers);
label = cpStr(d.label);
selections = d.selections;
playtime = d.playtime;
return *this;
}
void Classic::Report() const
{
Cd::Report();
std::cout << ", " << m_songs << std::endl;
}
Classic::Classic(const char* songs_list, const char* s1, const char* s2,
int n, double x) :Cd(s1, s2, n, x)
{
m_songs = cpStr(songs_list);
}
Classic::Classic(const Classic& c) :Cd(c)
{
m_songs = cpStr(c.m_songs);
}
Classic::~Classic()
{
delete[] m_songs;
}
Classic& Classic::operator=(const Classic& c)
{
if (this == &c)
return *this;
Cd::operator=(c);
delete[] m_songs;
m_songs = cpStr(c.m_songs);
return *this;
}
3,测试函数
测试函数不变
总结
提示:这里对文章进行总结:
1,new[],delete[]的使用
2,构造函数和析构函数
3,重载运算符的使用