在Setting a variable in a child class中,我試圖弄清楚如何正確地派生多態類中的變量。經過一些幫助後,我發現我需要在指針上使用dynamic_cast來正確訪問我需要的信息。我在這方面遇到了一些麻煩。正確執行動態轉換
這是我目前正在使用的功能。
void translateLines(Parser parser, Code code)
{
while(parser.hasMoreCommands())
{
vector<Command>::const_iterator it = parser.currentCommand();
if(it->commandType() == "A")
{
//SubType* item = dynamic_cast<SubType*>(*the_iterator);
A_COMMAND* a_command = dynamic_cast<A_COMMAND*>(*it); //line that is throwing the error
//string symbol = a_command->get_symbol();
//cout << "symbol: " << symbol << endl;
//perform binary conversion
}
/*else if(command.commandType() == "C")
{
string dest = command.get_dest();
}*/
//shouldn't be any L commands in symbol-less version
else
{
std::cout << "unexpected command value \n";
}
parser.advance();
}
}
這是我的Parser.h,它有關於向量的迭代器的相關信息。
#include "Command.h"
#include <vector>
class Parser {
private:
std::vector<Command> commands;
std::vector<Command>::const_iterator command_it = commands.begin();
public:
Parser(std::vector<std::string>);
bool hasMoreCommands() //are there more commands in the input?
{
if(command_it != commands.end())
return true;
else
return false;
}
void advance(){std::next(command_it);} //move to next command, should only work if hasMoreCommands returns false}
std::vector<Command>::const_iterator currentCommand(){return command_it;}
std::vector<std::string> translateCommands(); //convert commands into binary strings
};
以下是錯誤我收到:
g++ -O0 -g3 -Wall -c -fmessage-length=0 -std=c++11 -o Assembler.o "..\\Assembler.cpp"
..\Assembler.cpp: In function 'void translateLines(Parser, Code)':
..\Assembler.cpp:32:55: error: cannot dynamic_cast 'it.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator*<Command*, std::vector<Command> >()' (of type 'class Command') to type 'class A_COMMAND*' (source is not a pointer)
A_COMMAND* a_command = dynamic_cast<A_COMMAND*>(*it);
^
任何線索有什麼錯嗎?
編輯:所以我現在看到,我不能使用命令的向量,而是我需要指針的命令。我已經改變了Parser.h來處理vector<Command*>
而不是vector<Command>
。對於輸入我想是這樣的:
A_COMMAND command();
commands.push_back(&command);
但是,這不是很爲我工作,爲向量期待的指針,而不是引用。創建一個指向內存的指針並將其推入向量最簡單的方法是什麼?
錯誤消息提示'Command'是一個類名。這意味着你的整個想法是註定的。給派生類的'dynamic_cast'將總是失敗,因爲你的向量只包含精確的'Commands',而不是任何派生類型的對象。如果你想容器'包含'共享一個基類的不同類型的對象,容器必須是一個指針的容器 –
好吧,廢話,謝謝。 – Araganor