2016-08-16 43 views
1

我知道這個問題已被問了很多次,但沒有找到的答案能夠幫助我。我正在嘗試構建一個std::vector並用structs填充它。我想讓這些變量是靜態和常量的,所以它們可以很容易地傳遞。我的代碼現在的問題是:類中的C++ var沒有命名一個類型

Melodies.h

#ifndef Melodies_h 
#define Melodies_h 

#include "Arduino.h" 
#include <StandardCplusplus.h> 
#include <vector> 

struct Note { 
    int note; 
    int duration; 

    Note(int a, int b) : note(a), duration(b) {} 
}; 

struct Melody { 
    std::vector<Note> notes; 

    void addNote(Note note) { 
    notes.push_back(note); 
    } 
}; 

const Melody NONE; 
const Melody BILL; 
const Melody COIN; 
// this gives an error 
//COIN.addNote(Note(NOTE_C4, 5)); 

#endif 

Melodies.cpp

#include "Melodies.h" 
#include "Notes.h" 

// this gives an error 
//COIN.addNote(Note(NOTE_C4, 5)); 

我的錯誤(S):

error: 'COIN' does not name a type

我怎麼能存儲此類型的變量並將其設置爲1次,就像我想在begin函數中做的那樣?我不使用標準的C++ - 這是使用StandardCplusplus庫的Arduino。

+0

[Works on gcc](http://ideone.com/JYSP1S) – StoryTeller

+1

[MCVE]請。無論如何,你應該做一個簡單的初始化,不要使用任何'begin'函數,你的設計很奇怪。 – LogicStuff

+0

好吧,這是在我提到的使用StandardCplusplus庫的Arduino上。如果這與標準的gcc工作正常,那麼它一定是圖書館。我會盡量讓它更簡單,然後對於Arduino – shiznatix

回答

0

更新後的版本無法以這種方式工作 - 您無法更改常規類,也不能更改任何函數。

但是像這樣的作品(arduino.cc的Arduino IDE 1.6.9):

庫/旋律/ Melodies.h:

#ifndef Melodies_h 
#define Melodies_h 

#include "Arduino.h" 
#include <StandardCplusplus.h> 
#include <vector> 

struct Note { 
    int note; 
    int duration; 

    Note(int a, int b) : note(a), duration(b) {} 
}; 

using Melody = std::vector<Note>; 

extern const Melody NONE; 
extern const Melody BILL; 
extern const Melody COIN; 

#endif 

庫/旋律/ Melodies.cpp:

#include "Melodies.h" 
#include "Notes.h" 

const Melody NONE; 
const Melody BILL; 
const Melody COIN = {{NOTE_C4,20},{NOTE_E2,10}}; // whatever 

melodies_sketch/melodies_sketch.ino

#include <Melodies.h> 

void setup() { 
    // put your setup code here, to run once: 
    Serial.begin(57600); 

} 

void loop() { 
    Serial.println(COIN.size()); // just print size of Melodies vector 
    delay(1000); 
} 
0

當你聲明對象作爲const,你只能在初始化修改其成員的值。如果你可以在程序中的任何地方使用你的addNote()那麼COIN對象將不會是恆定的,是嗎?

您收到的錯誤似乎令人困惑,但嘗試使COIN爲非常量,或者添加一個構造函數,這將允許您在初始化時填充註釋向量。