Jos*_*ble 6 c++ oop inheritance
这是我的问题:我有一个.h文件中定义的虚方法,我想在一个继承自基类的类中调用它.遗憾的是,派生类中的方法不会被调用.有没有更好的方法来实现我正在尝试做的事情?
#ifndef ofxBASE_SND_OBJ
#define ofxBASE_SND_OBJ
#include "ofConstants.h"
class ofxBaseSndObj {
public:
virtual string getType(){}
string key;
};
#endif
Run Code Online (Sandbox Code Playgroud)
这是我的口碑课
#ifndef OFXSO_BUZZ
#define OFXSO_BUZZ
#include "ofxBaseSndObj.h"
class ofxSOBuzz : public ofxBaseSndObj
{
public:
string getType();
};
#endif
Run Code Online (Sandbox Code Playgroud)
ofxSOBuzz.cpp
string ofxSOBuzz::getType()
{
string s = string("ofxSOBuzz");
printf(" ********* returning string type %s", s.c_str()); // doesn't get called!
return s;
}
Run Code Online (Sandbox Code Playgroud)
然后在另一个类中我尝试这样称呼它:
string ofxSndObj::createFilter(ofxBaseSndObj obj)
{
string str = obj.getType();
if(str.compare("ofxSOBuzz") == 0)
{
printf(" all is well ");
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的方法中,我需要能够传递所有扩展ofxBaseSndObj对象的多种对象之一.任何建议或指示将不胜感激.谢谢!
Mar*_*ork 25
改变这一行:
string ofxSndObj::createFilter(ofxBaseSndObj obj)
Run Code Online (Sandbox Code Playgroud)
至
string ofxSndObj::createFilter(ofxBaseSndObj& obj)
Run Code Online (Sandbox Code Playgroud)
你正在做的是传递价值(传递副本).
这意味着您正在将对象复制到该函数.因为函数不知道你实际传递的是什么类型,所以它只传递函数声明中定义的类型,因此它会生成基类的副本(这就像切片问题一样).
解决方案是通过引用传递.
如果你不希望函数修改对象(也许这就是你传递值的原因所以它不能改变原文)然后传递一个const引用.
class ofxBaseSndObj
{
public:
virtual string getType() const;
// If the method does not change the object mark it const
string key;
};
string ofxSndObj::createFilter(ofxBaseSndObj const& obj)
{
// allowed to call this if getType() is a const
string str = obj.getType();
if(str.compare("ofxSOBuzz") == 0)
{
printf(" all is well ");
}
}
Run Code Online (Sandbox Code Playgroud)