使成员函数静态会使程序无法编译。想不通为什么

Making a member function static makes the program fail to compile. Can't figure out why

本文关键字:编译 想不通 为什么 程序 成员 函数 静态      更新时间:2023-10-16

我正在为arduino制作一个程序。我正在使用avr-g+4.9.2与STL从这里。

我有一节课鸡尾酒。我希望所有Cocktail类型的对象都能够访问指针向量。这些指针指向Alcohol类型的对象。由于这个指针向量对于Cocktail的每个实例都是相同的,所以我想使它成为静态的。但是,如果我使它们成为静态的,我的程序就无法编译。这是代码:

Ineb.hpp

class Alcohol
{
    private:
        float flow_rate_;
        Pump * which_pump_;
    public:
        std::string this_alcohol_;
        Alcohol(std::string this_alcohol, float flow_rate);
        Alcohol(std::string this_alcohol, float flow_rate, Pump which_pump);
        float HowLong(float percentage_of_drink, uint8_t drink_size); //How long in seconds the pump should be on
        void ChangeByteToRegister(uint8_t& byte_to_register);
};
class Cocktail
{
    private:
        bool order_matter_;
        uint8_t byte_to_register_;
        static std::vector<Alcohol*> alcohol_directory_; 
    public:
        static void test(Alcohol *ba) {alcohol_directory_.push_back(ba);} //STATIC KEYWORD HERE
        Cocktail(bool ordr_matter);
        std::vector<std::string> GetIngredients(const uint8_t& num_ingredients, PGM_P& string_table);
        uint8_t GetByteToRegister();
        void MakeDrink(const uint8_t& num_ingredients, PGM_P& string_table);
};

main.cpp

#include "src/Ineb.hpp"
#include "src/Pins.hpp"
#include "ingredients.h"
#include <pnew.cpp>
extern "C" void __cxa_pure_virtual() {
  for(;;);
}
int main(void) {
  init();
  setup();
  Ineb::Pump A(1,8);
  Ineb::Alcohol Vodka("vodka", 2.5, A);
  Ineb::Cocktail::test(&Vodka);
  for(;;)
    loop();
  return 0; // not reached
}

未定义对`Ineb::Cocktail::alcohol_directory_'的引用

我主要感到困惑的是,当我去掉静态时,为什么会编译它。静电在引擎盖下做什么??

类的static成员必须在类定义之外定义。

具有线路

std::vector<Alcohol*> Cocktail::alcohol_directory_; 

Cocktail.cpp中将执行此操作。