c-如何将子类的向量传递到需要父类向量的函数中?
作者:互联网
我可以将Child传递给需要Parent的成员函数,但是当使用向量时,出现编译错误,指出没有匹配的声明.请参阅底部对getUniqueLabels()的CorrelationEngineManager.cpp调用
ServerEvent.h
#ifndef SERVEREVENT_H
#define SERVEREVENT_H
#define SERVEREVENT_COLS 3
#include "Event.h"
#include <vector>
class ServerEvent: public Event {
private:
public:
ServerEvent(std::vector<std::string> tokens);
void print();
};
#endif
Event.h
#ifndef EVENT_H
#define EVENT_H
#include <string>
#define EVENT_STOP 0
#define EVENT_START 1
class Event {
private:
protected:
double time;
std::string label;
int type; // EVENT_START OR EVENT_STOP
public:
};
#endif
CorrelationEngineManager.h
class CorrelationEngineManager {
private:
std::vector<ServerEvent> s_events;
std::vector<UPSEvent> u_events;
std::vector<TimeRecord> s_timeRecords;
std::vector<TimeRecord> u_timeRecords;
// typeOfEvent gets type of event, 0 for error, look at #defines for codes
int typeOfEvent(std::vector<std::string>);
int createTimeRecords();
std::vector<std::string> getUniqueLabels(std::vector<Event> events);
public:
CorrelationEngineManager();
//~CorrelationEngineManager();
int addEvent(std::vector<std::string> tokens); //add event given tokens
void print_events();
};
CorrelationEngineManager.cpp
int CorrelationEngineManager::createTimeRecords() {
std::vector<std::string> u_sLabels; // unique server labels
std::vector<std::string> u_uLabels; // unique UPS labels
u_sLabels = getUniqueLabels(s_events);
// u_uLabels = getUniqueLabels(u_events);
return 1;
}
// returns a vector of unique labels, input a vector of events
std::vector<std::string> CorrelationEngineManager::getUniqueLabels(std::vector<Event> events) {
std::vector<std::string> temp;
return temp;
}
编译错误
CorrelationEngineManager.cpp: In member function ‘int CorrelationEngineManager::createTimeRecords()’:
CorrelationEngineManager.cpp:60: error: no matching function for call
to ‘CorrelationEngineManager::getUniqueLabels(std::vector<ServerEvent,
std::allocator<ServerEvent> >&)’ CorrelationEngineManager.h:23: note:
candidates are: std::vector<std::basic_string<char,
std::char_traits<char>, std::allocator<char> >,
std::allocator<std::basic_string<char, std::char_traits<char>,
std::allocator<char> > > >
CorrelationEngineManager::getUniqueLabels(std::vector<Event,
std::allocator<Event> >) make: *** [CorrelationEngineManager.o] Error 1
解决方法:
在C中这是不可能的,这需要称为协方差的功能.
即使类型A是类型B的子类,类型X A仍然是类型A.完全与X B类型无关.
因此,您不能通过std :: vector< UPSEvent>因为它们是不相关的类型,所以将其传递给期望std :: vector< Event>的函数.即使通过引用/指针传递也不起作用.
有两种方法可以解决此问题.
一种是使两个向量都持有指向Event的指针,然后它们将具有相同的类型.
另一个方法是,按照Daniel的建议,使函数成为模板函数.
正如Billz指出的那样,您还需要修复签名.
标签:c,vector,parent-child 来源: https://codeday.me/bug/20191011/1894058.html