12

(初学者程序员..)我遵循头文件的样式,它运行良好,但我试图弄清楚我在编译时如何不断收到所有这些错误。我在 Cygwin 中使用 g++ 进行编译。

Ingredient.h:8:13: error: expected unqualified-id before ‘)’ token
Ingredient.h:9:25: error: expected ‘)’ before ‘n’
Ingredient.h:19:15: error: declaration of ‘std::string <anonymous class>::name’
Ingredient.h:12:14: error: conflicts with previous declaration ‘std::string<anonymous class>::name()’
Ingredient.h:20:7: error: declaration of ‘int <anonymous class>::quantity’
Ingredient.h:13:6: error: conflicts with previous declaration ‘int<anonymous class>::quantity()’
Ingredient.h: In member function ‘std::string<anonymous class>::name()’:
Ingredient.h:12:30: error: conversion from ‘&lt;unresolved overloaded function type>’ to non-scalar type ‘std::string’ requested
Ingredient.h: In member function ‘int<anonymous class>::quantity()’:
Ingredient.h:13:25: error: argument of type ‘int (<anonymous class>::)()’ does not match ‘int’
Ingredient.h: At global scope:
Ingredient.h:4:18: error: an anonymous struct cannot have function members
Ingredient.h:21:2: error: abstract declarator ‘&lt;anonymous class>’ used as declaration

这是我的类头文件...

#ifndef Ingredient
#define Ingredient

class Ingredient {

public:
  // constructor
    Ingredient() : name(""), quantity(0) {} 
    Ingredient(std::string n, int q) : name(n), quantity(q) {}

  // accessors
    std::string name() { return name; }
    int quantity() {return quantity; }

  // modifier

private:
  // representation
  std::string name;
  int quantity;
};

#endif

我对这些错误感到困惑,并且真的不知道我在类的实现方面做错了什么..

4

2 回答 2

29

这很有趣。您实际上是在杀死您的班级名称#define Ingredient- 所有出现的Ingredient都将被删除。这就是为什么包含警卫通常采用#define INGREDIENT_H.

您还同时使用name了成员函数和 getter 函数(可能是为了翻译 C#?)。这在 C++ 中是不允许的。

于 2013-02-28T06:04:24.223 回答
4

如何查看错误?变量和函数不能有相同的名称。并且包含守卫永远不应该使用诸如类之类的名称。

#ifndef INGREDIENT_H
#define INGREDIENT_H

class Ingredient {

public:
  // constructor
    Ingredient() : name(""), quantity(0) {} 
    Ingredient(std::string n, int q) : name(n), quantity(q) {}

  // accessors
    std::string get_name() const { return name; }
    int get_quantity() const {return quantity; }

  // modifier

private:
  // representation
  std::string name;
  int quantity;
};

#endif
于 2013-02-28T06:05:20.370 回答