//classic.h
#ifndef CLASIC_H
#define CLASSIC_H
namespace CLASS
{
class Cd{
private:
char performers[50];
char label[20];
int selections;
double playtime;
public:
Cd(char* s1, char *s2,int n,double x);
Cd(const Cd &d);
Cd();
virtual ~Cd();
virtual void report()const;
Cd & operator =(const Cd &d); //有没有必要设置成虚函数,可以吗
};
class Classic: public Cd
{
private:
char work[50];
public:
Classic(char *s0,char *s1,char *s2,int n,double x);
Classic();
virtual ~Classic();
virtual void report ()const;
Classic & operator =(const Classic & c);
};
}
#endif
//classic.cpp
#include"classic.h"
#include<string>
#include<iostream>
namespace CLASS{
using std::endl;
using std::cout;
Cd::Cd(char *s1,char* s2,int n ,double x)
{
strcpy(performers,s1);
strcpy(label,s2);
selections=n;
playtime = x;
}
Cd::Cd(const Cd& d)
{
strcpy(performers,d.performers);
strcpy(label,d.label);
selections=d.selections;
playtime=d.playtime;
}
Cd::Cd()
{
performers[0]='\0';
label[0]='\0';
selections = 0;
playtime =0;
}
Cd::~Cd()
{
}
void Cd:: report() const
{
cout<<"perfomers: "<<performers<<endl;
cout<<"label: "<<label<<endl;
cout<<"selections: "<<selections<<endl;
cout<<"playtimes: "<<playtime<<endl;
}
Cd & Cd::operator=(const Cd &d)
{
strcpy(performers,d.performers);
strcpy(label,d.label);
selections=d.selections;
playtime=d.playtime;
return *this;
}
Classic:: Classic(char *s0,char *s1,char *s2,int n,double x):Cd(s1,s2,n,x)
{
strcpy(work,s0);
}
Classic::Classic():Cd()
{
work[0]='\0';
}
Classic:: ~Classic()
{
}
void Classic:: report ()const{
cout<<"work: "<< work<<endl;
Cd::report();
}
Classic & Classic:: operator =(const Classic & c)
{
Cd::operator=(c);
strcpy(work,c.work);
return *this;
}
}
//main.cpp
#include<iostream>
using namespace std;
#include"classic.h"
using CLASS::Cd;
using CLASS::Classic;
void Bravo (const Cd & disk);
int main()
{
Cd c1("Beatles","capitol",14,35.5);
Classic c2=Classic("piano somatia","alfred","phileps",2,58.17);
Cd* pcd=&c1;
cout<<"using object directly:\n";
c1.report();
c2.report();
cout<<"using type cd* pointer to object:\n";
pcd->report();
pcd=&c2;
pcd->report();
cout<<"calling a function with a cd reference argument:\n";
Bravo(c1);
Bravo(c2);
cout<<"testing assignment : ";
Classic copy;
copy =c2;
copy.report();
system("pause");
return 0;
}
void Bravo(const Cd & disk)
{
disk.report();
}
13.1
最新推荐文章于 2024-09-05 23:24:54 发布