shiznatix shiznatix - 3 months ago 24
C++ Question

C++ var in class does not name a type

I know this question has been asked many times but none of the answers I found have been able to help me. I am trying to build a

std::vector
and fill it in with
structs
. I want to make these variables static and constant, so they can be passed around easily. My code right now is:

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));


I get the error(s):


error: 'COIN' does not name a type


How can I store this type of variable and set it 1 time like I want to do in the
begin
function? I am not using standard c++ - this is on an Arduino using the StandardCplusplus library.

Answer

Updated version can't work in this way - you can't change const class and definitely not outside of any function.

However something like this works (arduino.cc Arduino IDE 1.6.9):

libraries/Melodies/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

libraries/Melodies/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);
}