因为不会经常用到,看完教程总忘。现在在这儿记录下来,以后看一下这里,就回忆起来,比较方便。上代码:
#include <iostream>
#include <string>
class Pet
{
public:
Pet(std::string theName);
void play();
protected:
std::string name;
};
class Cat : public Pet
{
public:
Cat(std::string theName);
void play();
};
class Dog : public Pet
{
public:
Dog(std::string theName);
void play();
};
Pet::Pet(std::string theName)
{
name = theName;
}
void Pet::play()
{
std::cout << name << "正在玩儿!\n";
}
Cat::Cat(std::string theName) : Pet(theName)
{
}
void Cat::play()
{
Pet::play();
std::cout << name << "玩毛线球!\n";
}
Dog::Dog(std::string theName) : Pet(theName)
{
}
void Dog::play()
{
Pet::play();
std::cout << name << "正在追赶那只该死的猫!\n";
}
int main()
{
Pet *cat = new Cat("加菲");
Pet *dog = new Dog("欧迪");
cat -> play();
dog -> play();
delete cat;
delete dog;
return 0;
}
这段代码出自小甲鱼的教程,mian里面用基类指针接收创建的子类对象,此时创建的子类对象被编译器识别的时候,类型还是基类,所以cat->play()和dog->play()调用的是基类的play(),而不是自己子类自己的play()。
运行结果如下:
加菲正在玩儿!
欧迪正在玩儿!
使用虚方法解决一下这个问题、、、
#include <iostream>
#include <string>
class Pet
{
public:
Pet(std::string theName);
virtual void play();
protected:
std::string name;
};
class Cat : public Pet
{
public:
Cat(std::string theName);
void play();
};
class Dog : public Pet
{
public:
Dog(std::string theName);
void play();
};
Pet::Pet(std::string theName)
{
name = theName;
}
void Pet::play()
{
std::cout << name << "正在玩儿!\n";
}
Cat::Cat(std::string theName) : Pet(theName)
{
}
void Cat::play()
{
Pet::play();
std::cout << name << "玩毛线球!\n";
}
Dog::Dog(std::string theName) : Pet(theName)
{
}
void Dog::play()
{
Pet::play();
std::cout << name << "正在追赶那只该死的猫!\n";
}
int main()
{
Pet *cat = new Cat("加菲");
Pet *dog = new Dog("欧迪");
cat -> play();
dog -> play();
delete cat;
delete dog;
return 0;
}
这段代码运行的结果就是:
加菲正在玩儿!
加菲玩毛线球!
欧迪正在玩儿!
欧迪正在追赶那只该死的猫!
把基类的play()声明成虚函数,在这种创建对象的情况下,就能执行子类的方法了。
析构器是虚方法