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

标签 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

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

最佳答案

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

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

关于c++ - 如何正确使用一个头文件成为一个完整的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15128559/

相关文章:

c++ - 将用户定义的类作为模板参数传递

c++ - 将 unsigned int 的三元组映射到 double——这是最优化/最有效的方法吗?

C++ 模板和访问命名空间

Java:Runnable 和方法的执行。他们应该在哪里?这有关系吗?

c++ - std::optional 和 boost::optional 是否遵守托管对象的对齐限制?

c++ - 如何将CLion C++项目导入Visual Studio?

c++ - 如何从 pthread ID 检索 pthread_key_t?

php - 从函数调用 PHP 对象方法

python - 复制对象时调用方法

javascript - 扩展错误 es6 类模块问题