How to properly use a header file to be a complete class?

前端 未结 2 2197
萌比男神i
萌比男神i 2021-02-20 00:45

(Beginner programmer..) I\'m following the style of a header file that worked fine, but I\'m trying to figure out how I keep getting all of these errors when I compile. I am com

相关标签:
2条回答
  • 2021-02-20 01:23

    That's a funny one. You are essentially killing your class name by #define Ingredient - all occurrences of Ingredient will be erased. This is why include guards generally take the form of #define INGREDIENT_H.

    You are also using name both for the member and the getter function (probably an attempt to translate C#?). This is not allowed in C++.

    0 讨论(0)
  • 2021-02-20 01:39

    How about look on errors? variables and functions can't have same names. And include guard should never names such as 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
    
    0 讨论(0)
提交回复
热议问题