gpt4 book ai didi

c++ - 不同对象的 vector ,对象具有非继承的功能

转载 作者:太空宇宙 更新时间:2023-11-04 16:16:59 25 4
gpt4 key购买 nike

<分区>

我想创建一个对象 vector ,很可能派生自基类,它可能有也可能没有自己的非派生函数。到目前为止,我无法调用这些函数,因为它们不是 vector 声明中使用的类的一部分。

如何才能使这成为可能?

下面的代码给出了错误:

../src/ObjectVectors.cpp:22:33: 错误:“BaseObject”中没有名为“getInt”的成员

//============================================================================
// Name : ObjectVectors.cpp
// Author : Edwin Rietmeijer
// Version :
// Copyright : This code is owned by Edwin Rietmeijer as of 2014
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include <vector>
#include "BaseObject.h"
#include "SubObjA.h"


using namespace std;

int main() {
vector<BaseObject *> objectVector;
objectVector.push_back( new SubObjA );



cout << objectVector.front() -> getInt() << endl;

// for ( pos = objectVector.begin(); pos != objectVector.end(); ++pos )
// cout << pos -> get() << endl;
}

/*
* BaseObject.h
*
* Created on: Feb 11, 2014
* Author: edwinrietmeijer
*/

#ifndef BASEOBJECT_H_
#define BASEOBJECT_H_

class BaseObject {
public:
BaseObject();
int get();
virtual ~BaseObject();
};

#endif /* BASEOBJECT_H_ */

/*
* BaseObject.cpp
*
* Created on: Feb 11, 2014
* Author: edwinrietmeijer
*/

#include "BaseObject.h"

BaseObject::BaseObject() {
// TODO Auto-generated constructor stub

}
int BaseObject::get(){
return 0;
}

BaseObject::~BaseObject() {
// TODO Auto-generated destructor stub
}

/*
* SubObjA.h
*
* Created on: Feb 11, 2014
* Author: edwinrietmeijer
*/

#ifndef SUBOBJA_H_
#define SUBOBJA_H_

#include "BaseObject.h"

class SubObjA : public BaseObject {
int data = 88;
public:
SubObjA();
int getInt();
virtual ~SubObjA();
};

#endif/* SUBOBJA_H_ */

/*
* SubObjA.cpp
*
* Created on: Feb 11, 2014
* Author: edwinrietmeijer
*/

#include "SubObjA.h"

SubObjA::SubObjA() {
// TODO Auto-generated constructor stub

}

int SubObjA::getInt() {
return data;
}

SubObjA::~SubObjA() {
// TODO Auto-generated destructor stub
}

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