C++virtual
时间: 2024-06-20 10:03:15 浏览: 12
C++中的virtual是一个关键字,主要用于实现多态性。在C++中,多态性可以通过虚函数来实现。虚函数是在基类中定义的函数,可以被派生类重新定义,实现基类指针或引用调用派生类对象的方法。当使用基类指针或引用调用虚函数时,会根据指向的对象类型来确定调用哪个函数。
举个例子,假设我们有一个基类Animal和两个派生类Dog和Cat,它们都有一个虚函数makeSound(),但是每个类实现的makeSound()函数不同。如果我们定义了一个指向Animal对象的指针,当我们调用makeSound()函数时,会根据指向的对象类型来确定调用哪个函数。
以下是一个简单的示例:
```
class Animal {
public:
virtual void makeSound() {
cout << "This is an animal sound." << endl;
}
};
class Dog : public Animal {
public:
void makeSound() {
cout << "Bark!" << endl;
}
};
class Cat : public Animal {
public:
void makeSound() {
cout << "Meow!" << endl;
}
};
int main() {
Animal *animal;
Dog dog;
Cat cat;
animal = &dog;
animal->makeSound(); // Output: Bark!
animal = &cat;
animal->makeSound(); // Output: Meow!
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)