使用多态子类各自的方法
我遇到了调用错误方法的问题。在我的程序中,我有 3 个类:符号、非终端和终端。 nonTerminal 和terminal 都是符号的子类。
在我的程序中,我只创建一个终端或非终端。以下是每个类的一些精简版本:
#ifndef SYMBOL_H
#define SYMBOL_H
#include <vector>
class terminal;
using namespace std;
class symbol {
public:
virtual vector<terminal> getFirstSet();
};
#endif
_
#ifndef NONTERMINAL_H
#define NONTERMINAL_H
#include "symbol.h"
#include "terminal.h"
#include <vector>
using namespace std;
class terminal;
class nonTerminal: public symbol {
public:
vector<terminal> getFirstSet();
};
#endif
_
#ifndef TERMINAL_H
#define TERMINAL_H
#include "symbol.h"
#include <vector>
using namespace std;
class terminal: public symbol {
public:
vector<terminal> getFirstSet();
};
#endif
我有这个函数:
bool addFirst(symbol s) {
vector<terminal> first = s.getFirstSet();
//....
}
但是,每当我使用终端或非终端调用它时,它总是使用 symbol::getFirstSet
方法。如何让它调用正确的 nonTerminal::getFirstSet
或 terminal::getFirstSet
方法?
I'm having an issue with the wrong method being called. In my program, I have 3 classes: symbol, nonTerminal, and terminal. nonTerminal and terminal are both subclasses of symbol.
In my program, I only ever create a terminal or nonTerminal. Here are some condensed versions of each class:
#ifndef SYMBOL_H
#define SYMBOL_H
#include <vector>
class terminal;
using namespace std;
class symbol {
public:
virtual vector<terminal> getFirstSet();
};
#endif
_
#ifndef NONTERMINAL_H
#define NONTERMINAL_H
#include "symbol.h"
#include "terminal.h"
#include <vector>
using namespace std;
class terminal;
class nonTerminal: public symbol {
public:
vector<terminal> getFirstSet();
};
#endif
_
#ifndef TERMINAL_H
#define TERMINAL_H
#include "symbol.h"
#include <vector>
using namespace std;
class terminal: public symbol {
public:
vector<terminal> getFirstSet();
};
#endif
I have this function:
bool addFirst(symbol s) {
vector<terminal> first = s.getFirstSet();
//....
}
However, anytime I call it with a terminal or nonTerminal, it always uses the symbol::getFirstSet
method. How can I get it to call the correct nonTerminal::getFirstSet
or terminal::getFirstSet
method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的函数addFirst正在按值接收您的对象。这意味着:
每次调用addFirst()时,都会创建一个新的符号对象,并从现有的终端或非终端复制.
为了解决这个问题并避免复制对象,请尝试通过引用传递对象:
Your function addFirst is receiving your object by value. What this means is that:
Every time you call addFirst() a new symbol object is created and copied from existing terminal or nonTerminal.
Whenever said copy occurs, the resulting object is neither terminal nor nonTerminal, but their base class - symbol.
To counter it, and to avoid copying the object, try passing your object by reference: