如何正确地使用头文件作为一个完整的类
How to properly use a header file to be a complete class?
(初学者…)我遵循头文件的风格,工作得很好,但我试图弄清楚我是如何在编译时不断得到所有这些错误的。我正在用g++在Cygwin中编译。
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
的形式。
您还将name
用于成员和getter函数(可能是尝试翻译c# ?)。这在c++中是不允许的
如何查看错误?变量和函数不能有相同的名称。并且include guard不应该使用class这样的名字。
#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
相关文章:
- 如何通过另一个对象中的命令正确地从一个对象返回数据
- 如果我的类正确地管理了一个资源,那么拥有智能的poointer有什么意义
- 正确地编写一个类,并将pthread与vlc库和c++一起使用
- 如何将一个字节数组正确地恢复为C 中的对象
- 如何正确地使一个对象拥有另一个多态对象
- 如何正确地从另一个文件调用函数
- 你如何正确地";"啪"的一声;到一个值
- 如何正确地 fread() 和 fwrite() 一个非文本文件?
- 正确地返回一个唯一的ptr
- 如何正确地将一个文本整数作为参数作为空指针进行传递,并使用其地址作为整数的实际值
- 如何正确地创建一个单例对象并在C++中使用它
- 问如何正确地做一个屏幕保护程序的功能窗口C++
- 如何在删除一个元素(double for循环)后正确地指向std::list
- 当传递给函数时,如何正确地将一个字符数组的内容复制到另一个字符数组,而不使用STL
- 是否有一种方法可以正确地比较一个float值是否大于/小于另一个
- 如何正确地将comparator传递给另一个模板函数
- 如何在c++中正确地赋值一个char*
- 如何正确地使用头文件作为一个完整的类
- wxWidgets:正确地制作一个包含其他控件的用户控件
- 文件变得非常大,需要将数据分离到另一个文件中,但也需要使用私有变量.我怎样才能正确地做到这一点