【问题标题】:'class': illegal use of this type as an expression how do I fix it?'class':非法使用这种类型作为表达式我该如何解决?
【发布时间】:2019-12-05 20:32:46
【问题描述】:

当我试图编译我的程序时,我得到了这些错误

1>c:\users\danilo\desktop\lab2\project1\project1\main.cpp(11): error C2275: 'Fighter': 非法使用这种类型作为表达式 1>c:\users\danilo\desktop\lab2\project1\project1\fighter.h(9): 注意:见'Fighter'的声明 1>c:\users\danilo\desktop\lab2\project1\project1\main.cpp(11): 错误 C2146: 语法错误: 在标识符 'f1' 之前缺少 ')' 1>c:\users\danilo\desktop\lab2\project1\project1\main.cpp(12): 错误 C2059: 语法错误: '}' 1>c:\users\danilo\desktop\lab2\project1\project1\main.cpp(12): 错误 C2143: 语法错误: 缺少';'在'}'之前

我的主文件如下所示:

#include "Fighter.h"
#include "Spell.h"
#include "Player.h"
#include "Wizard.h"
#include "Collection.h"

int lastID = 0;

int main{
    Fighter f1;
    f1("A", 100, 100);
}; 

我的 Fighter.h 看起来像这样

#define FIGHTER_H

#include "Card.h"
#include <string>
#include <iostream>
using namespace std;

class Fighter : public Card {
    int power;
public:
    virtual string getCategory() const override {
        return "FIGHTER";
    }
    int getPower() const {
        return power;
    }
    Fighter(string Name_, int neededEnergy_, int power_) : Card(Name_, neededEnergy_), power(power_) {}
    void operator>(const Fighter& f) const {
        if (this->getPower() > f.getPower()) {
            cout << this->getName() << " is stronger " << endl;
        }
        else {
            cout << f.getName() << " is stronger " << endl;
        };
    }
    virtual void write(ostream& it) const override {
        it << "(power: " << getPower() << ")";
    }
};


#endif FIGHTER_H

这里有什么问题?

【问题讨论】:

  • Fighter f1("A", 100, 100); - 这是对构造函数的调用。 Fighter f1; f1("A", 100, 100);这是给operator()()的电话
  • 你缺少main后面的括号它必须是main() { ... }而不是main{ ... }
  • Fighter.h 中缺少#ifndef

标签: c++ class


【解决方案1】:

您的 main 函数缺少括号。这个

int main{

应该是

int main(){

另外,f1("A", 100, 100) 不是构造函数调用,而是对 operator() 的调用,而您没有。改为这样做:

Fighter f1("A", 100, 100);

此外,请确保您的后卫始终如一。缺少一个#ifndef FIGHTER_H

【讨论】:

  • #pragma onceFighter.h 文件中也将受到欢迎
  • @Raffallo #pragma once 不是标准的,尽管大多数编译器都支持它。不过,您绝对正确地认为包含警卫存在问题。缺少#ifndef
  • 非常感谢,我有#ifndef,只是这里没有复制。
猜你喜欢
  • 1970-01-01
  • 2020-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多