c++ - 使成员函数静态化会使程序无法编译。不知道为什么

标签 c++ stl static arduino avr

<分区>

我正在为 arduino 制作一个程序。我正在使用 avr-g+ 4.9.2 和来自 here 的 STL .

我有一个类鸡尾酒。我希望 Cocktail 类型的所有对象都能够访问指针 vector 。这些指针指向酒精类型的对象。由于这个指针 vector 对于每个 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);
};

主要.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_”的 undefined reference

我主要困惑的是为什么在我去掉静态时编译。静态在幕后做什么?

最佳答案

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

有线

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

Cocktail.cpp 中将执行此操作。

关于c++ - 使成员函数静态化会使程序无法编译。不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30690194/

相关文章:

python - haskell 与 python 打字

c++ - 如何调用 DeviceIoControl 来检索它需要的内存量?

c++ - is_lock_free() 在升级到 MacPorts gcc 7.3 后返回 false

c++ - 如何将数组存储在 STL 列表中?

Java类关键字

Jekyll 静态评论系统

c++ - 非常大的 float 会导致不确定性吗?

c++ - 如何实现大尺寸非指针成员的 move 构造函数?

c++ - std string 通过迭代器比较两个子字符串

c++ - STL 中的 remove_neighbors 就像时尚