gpt4 book ai didi

C++ 使用迭代器访问 vector 的指针元素

转载 作者:搜寻专家 更新时间:2023-10-31 00:08:10 25 4
gpt4 key购买 nike

使用下面显示的代码,我创建了 4 个类(3 个子类和一个父类(super class)),每个类都具有相同的 print_info() 函数。我已经从每个类创建了指针对象,并将它们插入到使用父类(super class)创建的 vector 中。

#include <iostream>
#include <string>
#include <vector>
#include <iterator>

using namespace std;

class Vehicle
{
private:
int wheels, max_speed;
string model;
public:
virtual void print_info()
{
cout << "This is function print_info() in Vehicle (parent class)" << endl;
}
};

class Car: public Vehicle
{
private:
int doors, passengers;
public:
void print_info()
{
cout << "This is function print_info() in Car (child class)" << endl;
}
};

class Bike: public Vehicle
{
private:
string owner;
bool hasLights;
public:
string my_owner();
};

class Truck: public Vehicle
{
private:
float cargo_weight;
int allowed_speed;
public:
void print_info()
{
cout << "This is function print_info() in Truck (child class)" << endl;
}
};

int main()
{
Vehicle *v1 = new Vehicle();
Vehicle v2;
Car c1;
Car c2;
Bike b1;
Truck t1;
Truck t2;

vector <Vehicle> vvec;
Vehicle *v = new Vehicle();
Car *c = new Car();
Bike *b = new Bike();
Truck *t = new Truck();
vvec.push_back(*v);
vvec.push_back(*c);
vvec.push_back(*b);
vvec.push_back(*t);

vector<Vehicle>::iterator iter = vvec.begin();
while( iter != vvec.end())
{
iter->print_info();
iter++;
}

v1 = &v2;
v1->print_info();
v1 = &c2;
v1->print_info();
v1 = &t2;
v1->print_info();
system("pause");

return 0;
}

想要的输出是这样的:

这是Vehicle(父类)中的函数print_info

这是 Car(子类)中的函数 print_info

这是Vehicle(父类)中的函数print_info

这是 Truck(子类)中的函数 print_info

这是Vehicle(父类)中的函数print_info

这是 Car(子类)中的函数 print_info

这是 Truck(子类)中的函数 print_info

相反,我得到:

这是Vehicle(父类)中的函数print_info

这是Vehicle(父类)中的函数print_info

这是Vehicle(父类)中的函数print_info

这是Vehicle(父类)中的函数print_info

这是Vehicle(父类)中的函数print_info

这是 Car(子类)中的函数 print_info

这是 Truck(子类)中的函数 print_info

我认为这是由于早期绑定(bind)造成的,但我不知道如何解决!

最佳答案

您需要创建指针 vector vector <Vehicle*> vvec; , 当你 push_back 喜欢 vvec.push_back(*v);您按值传递元素并将其转换为 Vehicle , 因此不会存在多态性,因为 vector 的所有元素都只是简单的 Vehicle 对象,更改为:

//...
vector <Vehicle*> vvec;

Vehicle *v = new Vehicle();
Car *c = new Car();
Bike *b = new Bike();
Truck *t = new Truck();
vvec.push_back(v);
vvec.push_back(c);
vvec.push_back(b);
vvec.push_back(t);

vector<Vehicle*>::iterator iter = vvec.begin();
while( iter != vvec.end())
{
(*iter)->print_info();
iter++;
}
//...

你的输出将是:

This is function print_info() in Vehicle (parent class)
This is function print_info() in Car (child class)
This is function print_info() in Vehicle (parent class)
This is function print_info() in Truck (child class)
This is function print_info() in Vehicle (parent class)
This is function print_info() in Car (child class)
This is function print_info() in Truck (child class)

关于C++ 使用迭代器访问 vector 的指针元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50191322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com