如何正确使用头文件成为一个完整的类?

时间:2013-02-28 06:02:43

标签: c++ class

(初级程序员..)我正在遵循一个工作正常的头文件的样式,但我想弄清楚我在编译时如何继续得到所有这些错误。我正在使用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 ‘<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 ‘<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

我对这些错误感到困惑,并且真的不知道我对该类的实现有什么错误。

2 个答案:

答案 0 :(得分:25)

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

的形式

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

答案 1 :(得分: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