封装一个动物的基类,类中有私有成员:姓名,颜色,指针成员年纪
再封装一个狗类,共有继承于动物类,自己拓展的私有成员有:指针成员腿的个数,共有成员函数:叫
要求:完成类中的构造函数,析构函数,拷贝构造函数,拷贝复制函数
#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 << "Animal类有参构造函数" << endl;
}
~Animal()
{
cout << "Animal类析构函数" << endl;
delete age;
}
Animal(const Animal& other) :name(other.name), color(other.color), age(new int(*other.age))
{
cout << "Animal类拷贝构造函数" << endl;
}
Animal& operator=(const Animal& other)
{
cout << "Animal类拷贝赋值函数" << endl;
if (this != &other)
{
name = other.name;
color = other.name;
age = new int(*other.age);
}
return *this;
}
};
class Dog :public Animal
{
private:
int* count;
public:
Dog() {}
Dog(string name, string color, int age, int count) :Animal(name, color, age), count(new int(count))
{
cout << "Dog类有参构造函数" << endl;
}
~Dog()
{
cout << "Dog类析构函数" << endl;
delete count;
}
Dog(const Dog& other) :Animal(other), count(new int(*other.count))
{
cout << "Dog类拷贝构造函数" << endl;
}
Dog& operator=(const Dog& other)
{
cout << "Dogs类拷贝赋值函数" << endl;
if (this != &other)
{
Animal::operator=(other);
count = new int(*other.count);
}
return *this;
}
void speak()
{
cout << "汪汪汪" << endl;
}
};
int main()
{
Dog d1;
Dog d2("11", "0x6633ff", 3, 4);
Dog d3(d2);
d1 = d3;
return 0;
}
定义一个基类Animal,其中有一个虚函数perform(),用于在子类中实现不同的表演行为
#include <iostream>
using namespace std;
class Animal
{
protected:
string name;
int age;
string hobby;
public:
Animal() {}
Animal(string name, int age, string hobby) :name(name), age(age), hobby(hobby) {}
virtual void perform() = 0;
};
class Dog :public Animal
{
private:
int* count;
public:
Dog() {}
Dog(string name, int age, string hobby) :Animal(name, age, hobby) {}
void perform()
{
cout << "名称:" << this->name << endl;
cout << "年龄:" << this->age << endl;
cout << "爱好与表演:" << this->hobby << endl;
}
};
int main()
{
Dog d1("大黄", 3, "吃骨头");
Animal *animal = &d1;
animal->perform();
return 0;
}