[英]Expected primary expression before * C++
我无法在以下代码中找出错误
#include <iostream>
#include <vector>
using namespace std;
class Spell {
private:
string scrollName;
public:
Spell(): scrollName("") { }
Spell(string name): scrollName(name) { }
virtual ~Spell() { }
string revealScrollName() {
return scrollName;
}
};
class Fireball : public Spell {
private: int power;
public:
Fireball(int power): power(power) { }
void revealFirepower(){
cout << "Fireball: " << power << endl;
}
};
class SpellJournal {
public:
static string journal;
static string read() {
return journal;
}
};
string SpellJournal::journal = "";
void counterspell(Spell *spell) {
if((Fireball *firespell=dynamic_cast<Fireball*>(spell))!=NULL)
{
firespell->revealFirepower();
}
else
{
string scname=spell->revealScrollName();
int m = scname.size();
int n = SpellJournal::journal.size();
int L[m+1][n+1];
for(int i=0; i<=m; i++)
{
for(int j=0; j<=n; j++)
{
if(i==0 || j==0)
L[i][j] = 0;
else if(scname[i-1]==SpellJournal::journal[j-1])
L[i][j] = L[i-1][j-1]+1;
else
L[i][j] = max(L[i-1][j],L[i][j-1]);
}
}
cout<<L[m][n];
}
}
class Wizard {
public:
Spell *cast() {
Spell *spell;
string s; cin >> s;
int power; cin >> power;
if(s == "fire") {
spell = new Fireball(power);
}
else {
spell = new Spell(s);
cin >> SpellJournal::journal;
}
return spell;
}
};
int main() {
int T;
cin >> T;
Wizard Arawn;
while(T--) {
Spell *spell = Arawn.cast();
counterspell(spell);
}
return 0;
}
错误是语句中的*之前应包含主表达式
if((Fireball *firespell=dynamic_cast<Fireball*>(spell))!=NULL)
也
firespell' was not declared in this scope
我认为第二个错误与第一个有关。 我不知道我缺少什么概念。 我一直在关注此链接http://en.cppreference.com/w/cpp/language/dynamic_cast
请帮助。
if((Fireball *firespell=dynamic_cast(spell))!=NULL)
替换为
if(Fireball *firespell = dynamic_cast<Fireball*>(spell))
或
Fireball *firespell;
if( ( firespell = dynamic_cast(spell) ) != nullptr)
另外,我不知道此段是如何编译的。
int m = scname.size();
int n = SpellJournal::journal.size();
int L[m+1][n+1];
您不能在运行时声明数组大小,不能使用动态分配( malloc
, new
)或某些高级容器
编辑: 2号代码块中的可读性降低是一个有争议的声明。
从if
语句 :
] one of 条件[ ]之一
可以根据上下文转换为bool的表达式之一
用大括号或等于初始化程序声明单个非数组变量。
因此,您不能在单个if
语句中包含声明和布尔可转换表达式。
您必须先定义它, if
:
Fireball* firespell = dynamic_cast<Fireball*>(spell);
if (firespell != nullptr)
//Do something
如果它是C ++程序,那么您只需编写
void counterspell(Spell *spell) {
if( Fireball *firespell=dynamic_cast<Fireball*>(spell) )
{
firespell->revealFirepower();
}
由于声明是if语句中表达式的操作数,因此未编译原始代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.