C ++虚拟方法未按需调用 [英] C++ virtual method not called as desired

查看:110
本文介绍了C ++虚拟方法未按需调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被困住,已经试着解决这个虚拟问题,所以我请求你帮助我,因为它可能是一个愚蠢的训练的眼睛可以在几秒钟内解决。

I'm stuck and already tried a alot to solve this "virtual" problem and so I beg you to help me, cause it's probably something stupid that a "trained eye" can solve in seconds..

问题:当我在main中执行以下操作时:

The problem: When I do the following in main:

PrologConnector swiProlog;
swiProlog = PrologConnector::connectorFactory(PrologConnector::swi,argv);
swiProlog.send("blabla");

始终调用PrologConnector类的send方法,但不调用子类中的$ ..
您看到了问题吗?

always the send method of the PrologConnector class is called, but not the one from the subclass.. Do you see the problem?

感谢您的帮助!

b $ b PrologConnector.h

Here's the code: PrologConnector.h

class PrologConnector {
   virtual int send(char * cmd);
   virtual int init(char **argv);
   static PrologConnector connectorFactory(Prolog prolog, char ** argv);
};

PrologConnector.cpp

PrologConnector.cpp

int PrologConnector::send(char * argv) {
  std::cout << "not wanted"<<std::endl;
  return 0;
}


int PrologConnector::init(char **argv) {
  //TODO add implementation
  return 0;
}


PrologConnector PrologConnector::connectorFactory(Prolog prolog, char **argv) {
  if (prolog == swi) {
    SWIConnector sc;
    sc.init(argv);
    return sc;
  }

std::cout <<"Error in initialization!"<<std::endl;
PrologConnector pc;
return pc;
}



SWIConnector.h:

SWIConnector.h:

class SWIConnector : public PrologConnector {
  int send(char *cmd);
  int init(char **argv);
};

SWIConnector.cpp:

SWIConnector.cpp:

int SWIConnector::init(char **argv) {
//some action going on
}


int SWIConnector::send(char * cmd) {

//some action going on
}


推荐答案

你在这里是 对象切片 。要以多态方式使用对象,您可以通过指针或引用来访问它们。

What you have here is object slicing. In order to use objects polymorphically, you have to access them through a pointer or a reference.

您的工厂方法的签名应该更改以返回 PrologConnector * PrologConnector& ,之后您将可以看到预期的行为。

The signature of your factory method should be changed to return a PrologConnector* or PrologConnector&, after which you will be able to see the expected behavior.

这篇关于C ++虚拟方法未按需调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆