1.封装一个动物的基类,类中有私有成员:姓名,颜色,指针成员年纪再封装一个狗这样类,共有继承于动物类,自己拓展的私有成员有:指针成员:腿的个数(整型 int count),共有成员函数:会叫:void speak()要求:分别完成基类和派生类中的:构造函数、析构函数、拷贝构造函数、拷贝赋值函数eg : Dog d1;Dog d2(.....);Dog d3(d2);d1 = d3;
#include <iostream>
using namespace std;
class Animal
{
private:
string name;
string color;
int *age;
public:
Animal(){}
Animal(string name, string color, int age):name(name),color(color),age(new int(age))
{
cout << "父类有参构造函数" << endl;
}
~Animal()
{}
void speak()
{
cout << "汪汪" << endl;
}
Animal(const Animal &other):name(other.name),color(other.color),age(new int(*other.age))
{
cout << "Animal::拷贝构造函数" << endl;
}
Animal &operator=(const Animal &other)
{
//避免自己给自己赋值
if(this != &other)
{
name=other.name;
color=other.color;
age=new int(*other.age);
}
cout << "Animal::拷贝构造函数" << endl;
return *this;
}
void show()
{
cout << "name: " << name << endl;
cout << "age: " << *age << endl;
cout << "color: " << color << endl;
}
};
class Dog:public Animal
{
private:
int *tu;
public:
Dog(){}
Dog(int tu,string name,string color,int age):Animal(name,color,age),tu(new int(tu))
{
cout << "子类的有参构造"<<endl;
}
Dog(const Dog &other):Animal(other),tu(new int(*other.tu))
{
cout << "Dog::拷贝构造函数" << endl;
}
~Dog()
{
cout << "Dog::析构函数" << endl;
}
Dog &operator=(const Dog &other)
{
if(this != &other)
{
Animal::operator=(other);
tu = new int(*other.tu);
}
cout << "dog::拷贝赋值函数" << endl;
return *this;
}
void show()
{
cout <<"子类::show" << endl;
cout << *tu << endl;
}
};
int main()
{
Dog d1(4, "小黄", "黄" , 3);
Dog d2(d1);
Dog d3;
d3 = d2;
d3.speak();
d1.show();
d1.Animal::show();
return 0;
}
#include <iostream>
using namespace std;
class Animal
{
private:
string name;
string chc; //特征
public:
Animal(){}
Animal(string name,string chc):name(name),chc(chc)
{}
virtual void perform() = 0;
virtual ~Animal()
{
cout << "虚析构函数" << endl;
}
void show()
{
cout << name << endl;
cout << chc << endl;
}
};
class Lion:public Animal
{
private:
string name;
public:
Lion(){}
Lion(string name, string chc, string n):Animal(name,chc),name(n)
{}
void perform()
{
cout << "它表演吼叫,很有威慑力" << endl << endl;
}
~Lion()
{
cout << "Lion::虚构函数" << endl;
}
void show()
{
cout << name << endl;
}
};
class Elephant:public Animal
{
private:
string name;
public:
Elephant(){}
Elephant(string name,string chc, string n):Animal(name,chc),name(n)
{}
void perform()
{
cout << "它会用鼻子吃东西" << endl;
}
~Elephant()
{
cout << "Elephant::虚析构函数" << endl;
}
void show()
{
cout << name << endl;
}
};
int main()
{
Lion s("狮子" , "凶猛" , "不要靠近");
Animal *p = &s; //父类指针指向子类对象
s.Animal::show();
p->perform(); //重写虚函数
Elephant e("大象" , "鼻子长" ," 远离");
Animal *p1 = &e;
e.Animal::show();
p1->perform();
return 0;
}