gpt4 book ai didi

c++ - C++中的继承

转载 作者:可可西里 更新时间:2023-11-01 18:40:24 25 4
gpt4 key购买 nike

这是我的问题:我在 .h 文件中定义了一个虚拟方法,我想在从基类继承的类中调用它。遗憾的是,派生类中的方法没有被调用。有没有更好的方法来实现我想要做的事情?

#ifndef ofxBASE_SND_OBJ
#define ofxBASE_SND_OBJ

#include "ofConstants.h"

class ofxBaseSndObj {

public:

virtual string getType(){}

string key;

};

#endif

这是我的嗡嗡声课

#ifndef OFXSO_BUZZ
#define OFXSO_BUZZ

#include "ofxBaseSndObj.h"

class ofxSOBuzz : public ofxBaseSndObj
{
public:
string getType();
};

#endif

ofxSOBuzz.cpp

string ofxSOBuzz::getType()
{
string s = string("ofxSOBuzz");
printf(" ********* returning string type %s", s.c_str()); // doesn't get called!
return s;
}

然后在另一个类中我尝试这样调用它:

string ofxSndObj::createFilter(ofxBaseSndObj obj)
{
string str = obj.getType();
if(str.compare("ofxSOBuzz") == 0)
{
printf(" all is well ");
}
}

在上面的方法中,我需要能够传入多种对象中的一种,这些对象都扩展了 ofxBaseSndObj 对象。任何建议或指示将不胜感激。谢谢!

最佳答案

改变这一行:

string ofxSndObj::createFilter(ofxBaseSndObj obj)

string ofxSndObj::createFilter(ofxBaseSndObj& obj)

你所做的是按值传递(传递拷贝)。

这意味着您正在将对象复制到函数中。因为该函数不知道您实际传递的是什么类型,所以它只传递函数声明中定义的类型,因此它复制了基类(这被称为 slicing 问题)。

解决方案是通过引用传递。

如果您不希望函数修改对象(也许这就是您按值传递的原因,因此它不能改变原始对象),那么传递一个常量引用。

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 ");
}
}

关于c++ - C++中的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/237027/

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