[英]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.