1、试编程
封装一个动物的基类,类中有私有成员:姓名,颜色,指针成员年纪再封装一个狗这样类,共有继承于动物类,自己拓展的私有成员有:指针成员:腿的个数(整型intcount),共有成员函数:会叫:void speak()
要求:分别完成基类和派生类中的:构造函数、析构函数、拷贝构造函数、拷贝赋值函数
#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()
{
cout << "析构函数" << endl;
}
//拷贝构造函数
Animal(const Animal &other):name(other.name),color(other.color),age(new int(*other.age))
{
cout << "父类:拷贝构造函数" << endl;
}
//拷贝赋值函数
Animal &operator=(const Animal &other)
{
if(this != &other)
{
name = other.name;
color = other.name;
age = new int(*other.age);
}
cout << "父类:拷贝赋值函数" << endl;
return *this;
}
};
class Dog:public Animal
{
private:
int *leg;
public:
Dog(){}
Dog(string name,string color,int age,int leg):Animal(name,color,age),leg(new int(leg))
{
cout << "dog 有参构造函数" << endl;
}
Dog(const Dog &other):Animal(other),leg(new int (*other.leg))
{
cout << "dog 拷贝构造函数" << endl;
}
Dog &operator=(const Dog &other)
{
if(this != &other)
{
Animal::operator=(other);
leg = new int(*other.leg);
}
cout << "dog 拷贝赋值函数" << endl;
return *this;
}
void speak()
{
cout << "汪汪汪" <<endl;
}
~Dog()
{
cout << " dog 析构函数" << endl;
}
};
int main()
{
Dog d1;
Dog d2("小蒜","yellow",2,4);
Dog d3(d2);
d1 = d3;
return 0;
}
2、试编程
具体过程如下:
定义一个基类 Animal,其中有一个虚函数perform(),用于在子类中实现不同的表演行为。
#include <iostream>
using namespace std;
class Animal
{
private:
string name;
public:
Animal(){}
Animal(string name):name(name)
{
}
virtual void perform()
{
cout << "I am performer!" << endl;
}
};
class lion:public Animal
{
private:
string name;
public:
lion(){}
lion(string n1,string n2):Animal(n1),name(n2)
{
}
void perform()
{
cout << "I am lion,I am strong!" << endl;
}
};
class elephant:public Animal
{
private:
string name;
public:
elephant(){}
elephant(string n1,string n2):Animal(n1),name(n2){}
void perform()
{
cout << "I am elephant,Look at my nose!" << endl;
}
};
int main()
{
lion l1("小蒜","小狮子");
Animal *p = &l1;
p->perform();
elephant e1("小蒜","小象");
Animal *q = &e1;
q->perform();
return 0;
}
思维导图