基类定义如下: class animal { public: virtual void voice()=0; }; 定义猫和狗两个继承类,然后在向量容器中放入动态生成的一只猫对象和一只狗对象(基于多态方式,即把基类指针存入向量容器); 而后
时间: 2024-03-25 17:37:10 浏览: 19
可以通过以下代码来遍历容器中的每个动物对象并调用它们的voice()函数:
```
#include <iostream>
#include <vector>
using namespace std;
class animal {
public:
virtual void voice() = 0;
};
class cat : public animal {
public:
virtual void voice() {
cout << "Meow!" << endl;
}
};
class dog : public animal {
public:
virtual void voice() {
cout << "Woof!" << endl;
}
};
int main() {
vector<animal*> animals;
animals.push_back(new cat());
animals.push_back(new dog());
for (int i = 0; i < animals.size(); i++) {
animals[i]->voice();
}
return 0;
}
```
输出结果为:
```
Meow!
Woof!
```
相关问题
基类定义如下: class animal { public: virtual void voice()=0; }; 定义猫和狗两个继承类,然后在向量容器中放入动态生成的一只猫对象和一只狗对象(基于多态方式,即把基类指针存入向量容器); 而后通过迭代器访问容器内对象并调用对应函数,不能有内存泄露。
好的,这是一个关于多态的问题,我来给你解答。
首先,让我们定义猫和狗两个继承类:
```c++
class Cat : public animal {
public:
void voice() override {
std::cout << "Meow!" << std::endl;
}
};
class Dog : public animal {
public:
void voice() override {
std::cout << "Woof!" << std::endl;
}
};
```
接着,我们可以声明一个向量容器,并把动态生成的一只猫对象和一只狗对象(基于多态方式,即把基类指针存入向量容器)放入容器中:
```c++
std::vector<animal*> animals;
animals.push_back(new Cat());
animals.push_back(new Dog());
```
然后,我们可以通过迭代器访问容器内对象并调用对应函数:
```c++
std::vector<animal*>::iterator it;
for (it = animals.begin(); it != animals.end(); it++) {
(*it)->voice();
}
```
最后,我们需要释放动态分配的内存,避免内存泄露:
```c++
for (it = animals.begin(); it != animals.end(); it++) {
delete *it;
}
```
完整代码如下:
```c++
#include <iostream>
#include <vector>
class animal {
public:
virtual void voice() = 0;
};
class Cat : public animal {
public:
void voice() override {
std::cout << "Meow!" << std::endl;
}
};
class Dog : public animal {
public:
void voice() override {
std::cout << "Woof!" << std::endl;
}
};
int main() {
std::vector<animal*> animals;
animals.push_back(new Cat());
animals.push_back(new Dog());
std::vector<animal*>::iterator it;
for (it = animals.begin(); it != animals.end(); it++) {
(*it)->voice();
}
for (it = animals.begin(); it != animals.end(); it++) {
delete *it;
}
return 0;
}
```
希望我的回答对你有帮助!
针对以下程序,哪个选项会出现编译错误 class A { public: virtual void Print( ) = 0 ; private: int a; };
这段程序定义了一个抽象基类 A,其中包含一个纯虚函数 Print() 和一个私有成员变量 a。由于 Print() 是纯虚函数,A 类是抽象类,不能被直接实例化。
在这段程序中,a 是私有成员变量,只能在类的内部访问,不能被外部访问。这个类的设计并没有问题,不会出现编译错误。
但是,如果在类的内部定义一个使用 a 的函数,而该函数是公有函数,那么编译器会报错,因为私有成员变量只能在类的内部访问,外部无法访问。例如:
```c++
class A {
public:
virtual void Print() = 0;
void Func() { a = 10; } // 编译错误,a 是私有的
private:
int a;
};
```
这样的话,编译器会提示“error: ‘int A::a’ is private within this context”。