实例的全局初始化

时间:2019-02-21 23:25:24

标签: c++

我需要创建实例的 global 初始化。

untitled.ino

#include "own_library.h"
own_library test(1, 2, 3);

void setup() {
} 

void loop() {
}

own_library.h

#ifndef own_library_h
#define own_library_h

class own_library {
   public:
       own_library(byte one, byte two, byte three);
   private:
};

#endif

own_library.cpp

#include <foreign_library.h>

#include "own_library.h"

own_library::own_library(byte one, byte two, byte three) {
    foreign_library test = foreign_library(one, two, three);
}

// i need to work with foreign library under this comment //

主要问题是,实例是在构造函数中创建的,就像本地实例一样。

1 个答案:

答案 0 :(得分:0)

您不太可能需要全局实例,而是希望在您自己的整个类中都可以访问您的外部库对象,为此,您应该使用member initialization list和而是在构造函数成员初始化列表中初始化foreign_library,这样,您就可以在整个库中对其进行访问,这就是我想的。

所以您可以这样做:

own_library.h:

#ifndef own_library_h
#define own_library_h

#include <foreign_library.h>

class own_library {
   public:
       own_library(byte one, byte two, byte three);
   private:
       foreign_library test; // Member variable, so accessible throughout class.
};

#endif

own_library.cpp:

#include "own_library.h"

// Initialization list added to constructor.
own_library::own_library(byte one, byte two, byte three) : test {one, two, three} {
   // This is now empty here.
}
相关问题