Arduino C++ vector of int - c++

I have a class named Model and in ypur .h file I have this:
private:
vector<int> memory(MEMORY_SIZE);
MEMORY_SIZE is a const in a define header with value 10.
when I try compile I'm gettind this error code
Model.h:33: error: ISO C++ forbids declaration of 'vector' with no type
Model.h:33: error: expected ';' before '<' token
I don't know why this, I'm declaring the type of vector...
The complete header code:
/*
* Model.h
*
* Created on: Sep 13, 2012
* Author: ademar
*/
#ifndef MODEL_H_
#define MODEL_H_
#include "Config.h"
#include "Arduino.h"
#include <vector>
class Model {
public:
Model(int pin, char command[]);
Model(int pin, int initialState, char command[]);
bool isChanged(int currentState);
char* getCommand(void);
int getState();
void setRange(int range);
void usesMemory();
private:
int pin;
int state;
int range;
long time;
char* command;
void updateTime();
bool useMemory;
std::vector<int> memory;
};
#endif /* MODEL_H_ */
And the C++ code:
/*
* Model.cpp
*
* Created on: Sep 13, 2012
* Author: ademar
*/
#include "Model.h"
Model::Model(int pin, char command[]) {
*this = Model(pin,0,command);
}
Model::Model(int pin, int initialState, char command[]) {
this->pin = pin;
this->state = initialState;
this->command = command;
this->range = 1;
this->useMemory = false;
this->updateTime();
}
void Model::usesMemory(){
this->useMemory = true;
}
void Model::setRange(int range){
this->range = range;
}
bool Model::isChanged(int currentState) {
if ((currentState >= (this->state + this->range) || currentState <= (this->state - this->range)) && ((this->time+WAIT_CHANGE)<millis())){
this->state = currentState;
updateTime();
return true;
}
return false;
}
char* Model::getCommand(){
return this->command;
}
int Model::getState(){
return this->state;
}
void Model::updateTime(){
this->time = millis();
}
And the error:
In file included from Honda.h:11,
from Honda.cpp:8:
Model.h:33: error: ISO C++ forbids declaration of 'vector' with no type
Model.h:33: error: invalid use of '::'
Model.h:33: error: expected ';' before '<' token

These are my shots that vector is not included or you are missing namespace std::. The compiler explicitly points out that it does not know what vector is.
What is more, you don't initialize fields like this in C++. You have to do it in the constructor:
#include <vector>
#include <iostream>
#define MEMORY_SIZE 10
class Clazz {
std::vector<int> memory;
public:
Clazz() : memory(MEMORY_SIZE){}
int memory_size() {return memory.size();}
};
int main() {
Clazz c;
std::cout << c.memory_size() << std::endl;
return 0;
}

Related

Parsing array in library constructor - Pointer problem (C++)

I am trying to develop an Arduino library that consists out of two classes. I want 'WayPointStack' to store an array of 'WPCommand', but I can't get it to work.
It is obviously a pointer problem, but I don't know how to solve it. There are four errors left in my code:
WayPointStack.cpp:23:7: error: incompatible types in assignment of 'WPCommand*' to 'WPCommand [0]'
_wp = new WPCommand[arrSize]; //Fixed
WayPointStack.cpp:44:34: error: could not convert '(operator new(16u), (((WPCommand*)<anonymous>)->WPCommand::WPCommand(4, 10000), ((WPCommand*)<anonymous>)))' from 'WPCommand*' to 'WPCommand'
return new WPCommand(_END, 10000);
WayPointStack.cpp:59:15: error: no match for 'operator=' (operand types are 'WPCommand' and 'WPCommand*')
_wp[pointer] = new WPCommand(target, time); # Fixed
WPCommand.h:10:7: note: candidate: WPCommand& WPCommand::operator=(const WPCommand&)
class WPCommand # Does not appear anymore, fixed
WPCommand.h
#ifndef WPCommand_h
#define WPCommand_h
#include "Arduino.h"
class WPCommand
{
public:
WPCommand(int target, int time );
WPCommand();
int GetTarget();
int GetTime();
int LEFT;
int RIGHT;
int FORWARD;
int BACKWARD;
int STOP;
int END;
private:
int _target;
int _time;
};
#endif
WayPointStack.h
#ifndef WayPointStack_h
#define WayPointStack_h
#include "Arduino.h"
#include "WPCommand.h"
class WayPointStack
{
public:
WayPointStack();
WayPointStack(WPCommand wp[], int length);
WPCommand GetNextWP();
WPCommand GetWP(int i);
void AddWP(int target, int time);
int SetWPPointer(int i);
int GetWPPointer();
int GetLength();
private:
WPCommand _wp[];
int pointer;
int _length;
};
#endif
WayPointStack.cpp (partly)
#include "Arduino.h"
#include "WayPointStack.h"
#include "WPCommand.h"
#define _BACKWARD 0
#define _FORWARD 1
#define _STOP 2
#define _LEFT 3
#define _RIGHT 4
#define _END 4
#define arrSize 100
WayPointStack::WayPointStack()
{
_wp = new WPCommand[arrSize];
_length = 0;
pointer = 0;
}
WayPointStack::WayPointStack(WPCommand wp[], int length)
{
_wp = new WPCommand[arrSize];
for (int i = 0; i < length; i++){
_wp[i] = wp[i];
}
_length = length;
pointer = 0;
}
WPCommand WayPointStack::GetNextWP()
{
if (pointer < _length){
pointer++;
return _wp[pointer-1];
}
return new WPCommand(_END, 10000);
}
I tried to more or less randomly reference and derefence _wp and wp[] but it did not work.
Edit:
Changing
WPCommand _wp[];
to
WPCommand *_wp;
successfully fixed the first error. Doing the same to
WayPointStack(WPCommand *wp, int length);
Edit:
_wp[pointer] = WPCommand(target, time);
instead of
_wp[pointer] = new WPCommand(target, time);
successfully fixed error number 3.
Edit:
return WPCommand(_END, 10000);
fixed error number 2.
Problem solved.

c++ how should a core game class call constructs from other files

Im trying to create the core in main , then create x Players. I would like to follow the singleton structure for the other classes that i will code but I would like to get to the root of the cause of this error I'm receiving from the compiler. I have tried different approaches to trying to solve but I'm new to c++ so this making things extremely difficult.
These are the errors I'm receiving
errors
./Core.h:18:39: error: expected '(' for function-style cast or type construction
CreateNewPlayer(std::string ScreenName, int ID) {
~~~~~~~~~~~ ^
./Core.h:18:55: error: expected '(' for function-style cast or type construction
CreateNewPlayer(std::string ScreenName, int ID) {
~~~ ^
app.cpp:10:11: error: no member named 'CreateNewPlayer' in 'Core'
CoreObj.CreateNewPlayer("DONKEYSHARK", 1);
app.cpp
#include "Core.h"
#include "player.h"
int main()
{
Core CoreObj;
CoreObj.CreateNewPlayer("screenname", 1) PlayerOne;
std::cout << CoreObj.GetPlayerScreenName(PlayerOne) << "\n";
std::cout << CoreObj.GetPlayerID(PlayerOne) << "\n";
return 0;
}
Core.h
include<iostream>
#include"Player.h"
#include <vector>
#ifndef Core_H
#define Core_H
class Core{
private:
public:
/* The CORE is Managing all the objects so it needs to know what job in what sector its going to perform in
the first parameter will be what sector, second task, third data*/
Core(int x = 0, std::string y = "New"){
/* Need to know which sector the task belongs to, Becuase this class is going to get complex Qucikly */
switch(x){
case 0:
CreateNewPlayer(std::string ScreenName, int ID) {
Player(ScreenName, ID) Player;
return Player&;
}
break;
default:
/* log function*/
break;
}
}
int GetPlayerID(Player& Player){
return Player.GetID();
}
std::string GetPlayerScreenName(Player& Player){
return Player.GetScreenName();
}
};
#endif /*Core_H*/
Player.h
include <iostream>
#ifndef Player_H
#define Player_H
class Player {
private:
std::string ScreenName, SignUpDate, PublicKey, PrivateKey;
int PlayerID, CreditBalance, GlobalRank, RegionalRank, localRank;
friend class Core Player(std::string, int);
public:
int TotalPlayers = 0, TotalLivePlayers = 0;
static std::string GetScreenName();
static int GetID();
Player(std::string Screenname, int ID){
this->ScreenName = Screenname;
this->PlayerID = ID;
TotalPlayers++;
TotalLivePlayers++;
}
}
player.cpp
#include <iterator>
#include <iostream>
#include <ctime>
#include "PlayerKeys.h"
class Player {
private:
std::string ScreenName, SignUpDate, PublicKey, PrivateKey;
int PlayerID, CreditBalance, GlobalRank, RegionalRank, localRank;
static int TotalPlayers, TotalLivePlayers;
public:
static int GetTotalNumbOfPlayer(){return TotalPlayers;}
static int GetTotalNumbOfLivePlayer(){return TotalLivePlayers;}
int GetID(){return PlayerID;}
std::string GetScreenName(){return ScreenName;}
Player(){
/* overload*/
}
static int GetTotalNumbOfLivePlayer(){return TotalLivePlayers;}
static int GetTotalNumbOfPlayer(){return TotalPlayers;}
~Player();
}
core.cpp
#include<iostream>
#include"Player.h"
/* core auto Deck = GetDeck();
// std::copy(Deck.begin(), Deck.end(), std::ostream_iterator<std::string>(std::cout, " "));
std::cout << "\n";*/
class Core{
/* As a security measure when core functionality needs the daily hash values */
public:
std::string Core::DevlopmentTeamAccessDailyHash(){
return "DailyHAshValueTest"
}
std::sting Core::SystemAccessActiveHash(){
return "SystemHAshValueTest"
}
std::string Core::CurrentDateAndTime(){
time_t rawtime;
struct tm * timeinfo;
char buffer[80];
time (&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer,sizeof(buffer),"%d-%m-%Y %H:%M:%S",timeinfo);
std::string str(buffer);
return str;
}
}

Expected unqualified-id before 'int'

I'm trying to make an Arduino library, for a build that I'm going to be using throughout a few sketches, and I haven't been able to figure out why I keep getting this error. Searching on multiple forums, comes up with no working answers. This is my code:
charLCD.h:
#ifndef charLCD
#define charLCD
#include "Arduino.h"
class charLCD
{
public:
charLCD(int pin1,int pin2,int pin3,int pin4,int enable);
void sendChar(unsigned char c);
private:
int _pin1;
int _pin2;
int _pin3;
int _pin4;
int _enable;
};
#endif
charLCD.cpp:
#include "Arduino.h"
#include "charLCD.h"
#include <limits.h>
charLCD::charLCD(int pin1,int pin2,int pin3,int pin4,int enable) {
_pin1 = pin1;
_pin2 = pin2;
_pin3 = pin3;
_pin4 = pin4;
_enable = enable;
}
void sendChar(unsigned char c) {
// Send char to item
}
char* chartobin ( unsigned char c )
{
static char bin[CHAR_BIT + 1] = {0};
int i;
for ( i = CHAR_BIT - 1; i >= 0; i-- )
{
bin[i] = (c % 2) + '0';
c = c/2;
}
return bin;
}
The problem is on the line where I define the constructor in the header.
Because of
#define charLCD
this is what your compiler sees:
class
{
public:
(int pin1,int pin2,int pin3,int pin4,int enable);
void sendChar(unsigned char c);
private:
int _pin1;
int _pin2;
int _pin3;
int _pin4;
int _enable
};
::(int pin1,int pin2,int pin3,int pin4,int enable) {
_pin1 = pin1;
_pin2 = pin2;
_pin3 = pin3;
_pin4 = pin4;
_enable = enable;
}
// ...
Pick a better header guard.
You also need to qualify the definitions of member functions:
void charLCD::sendChar(unsigned char c) {
// Send char to item
}

undeclared identifier, object vector

I am getting an error and I don't know how to fix it. I checked everything and maybe I overlooked something, but I am not able to find the problem.
Errors:
1>------ Build started: Project: Aquarium, Configuration: Release x64 ------
1> Fish.cpp
1>c:\users\lloyd17\dropbox\aquarium project\aquarium\aquarium\EntityControl.h(21): error C2065: 'Fish': undeclared identifier
1>c:\users\lloyd17\dropbox\aquarium project\aquarium\aquarium\EntityControl.h(21): error C2059: syntax error: '>'
1>c:\users\lloyd17\dropbox\aquarium project\aquarium\aquarium\EntityControl.h(21): error C2976: 'std::vector': too few template arguments
1> C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\vector(682): note: see declaration of 'std::vector'
1>c:\users\lloyd17\dropbox\aquarium project\aquarium\aquarium\EntityControl.h(24): error C2061: syntax error: identifier 'Fish'
1> LooseCalculationClass.cpp
1>c:\users\lloyd17\dropbox\aquarium project\aquarium\aquarium\EntityControl.h(21): error C2065: 'Fish': undeclared identifier
1>c:\users\lloyd17\dropbox\aquarium project\aquarium\aquarium\EntityControl.h(21): error C2059: syntax error: '>'
1>c:\users\lloyd17\dropbox\aquarium project\aquarium\aquarium\EntityControl.h(21): error C2976: 'std::vector': too few template arguments
1> C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\vector(682): note: see declaration of 'std::vector'
1>c:\users\lloyd17\dropbox\aquarium project\aquarium\aquarium\EntityControl.h(24): error C2061: syntax error: identifier 'Fish'
1>LooseCalculationClass.cpp(7): warning C4551: function call missing argument list
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Fish.h
#pragma once
#include <iostream>
#include <string>
#include "EntityControl.h"
class Fish
{
private:
//location of the fish
unsigned int _xLocation = 0, _yLocation = 0, _zLocation = 0;
//name of fish
std::string nameOfFish;
unsigned int speed;
public:
//constructor
Fish(std::string name, unsigned int fishSpeed)
{
nameOfFish = name;
speed = fishSpeed;
}
//getters
int getX() const;
int getY() const;
int getZ() const;
std::string getName() const;
void changeX(unsigned int x);
void changeY(unsigned int y);
void changeZ(unsigned int z);
void move();
~Fish();
};
Fish.cpp
#include "Fish.h"
int Fish::getX() const
{
return _xLocation;
}
int Fish::getY() const
{
return _yLocation;
}
int Fish::getZ() const
{
return _zLocation;
}
std::string Fish::getName() const
{
return nameOfFish;
}
void Fish::changeX(unsigned int x)
{
_xLocation = x;
}
void Fish::changeY(unsigned int y)
{
_yLocation = y;
}
void Fish::changeZ(unsigned int z)
{
_zLocation = z;
}
void Fish::move()
{
EntityControl entity;
unsigned int x = rand() % entity.getXContainer();
unsigned int y = rand() % entity.getYContainer();
unsigned int z = rand() % entity.getZContainer();
}
Fish::~Fish()
{
}
Aquarium.cpp(Main)
using namespace std;
#include "EntityControl.h"
#include <Windows.h>
#include <time.h>
#include "LooseCalculationClass.h"
#include <thread>
#include "Fish.h"
int main() {
/*Not using new in object definitions so I don't have to delete them afterwards since pointers don't stay in memory*/
bool running = true;
//defining my objects for functions
EntityControl entity;
LooseCalculationClass calc;
vector<Fish*> fishVector;
Fish a("Lloyd", 200);
fishVector.push_back(&a);
std::thread t1(&EntityControl::movementController, entity, &fishVector);
//std::thread t2(&LooseCalculationClass::userInput, calc);
//t2.detach();
t1.detach();
//main gameloop, prints out the results for every fish, waits a bit and then refreshes the screen
while(running){
for (auto Fish_ptr : fishVector) {
calc.printOutXYZ(*Fish_ptr);
Sleep(500000);
system("pause");
//system("cls");
}
}
return 0;
}
EntityControl.h
#pragma once
#include <iostream>
#include <vector>
#include "Fish.h"
#include <random>
#include <array>
#include <Windows.h>
class EntityControl
{
private:
/*Didn't make a separate object because I only
needed the x,y,z of the fish container although it is against the rules of object oriented programming*/
const unsigned int _xContainer = 20;
const unsigned int _yContainer = 60;
const unsigned int _zContainer = 40;
public:
/*grabs the location of a vector of fish pointers, then takes the
vector and accesses every object threw it's data location with dereferencing.
(Controls the movement of the fish and prevents collision)*/
void movementController(std::vector<Fish*> *fishInputVector);//thread!!
//ACHTUNG! fishInput is the fish to check the surrounding of, changing this might bring up unexpected errors
bool CheckCollision(Fish* fishInput , Fish* fishInput2);
int getXContainer() const;
int getYContainer() const;
int getZContainer() const;
~EntityControl();
};
EntityControl.cpp
#include "EntityControl.h"
/*if the container was much larger,
then multiple threads would be a better solution*/
void EntityControl::movementController(std::vector<Fish*> * fishInputVector)
{
while (true) {
for (auto fish_ptr : *fishInputVector) {
}
}
}
bool EntityControl::CheckCollision(Fish * fishInput, Fish * fishInput2)
{
//collision true/false
bool collision = false;
//collision detectors
bool xCollision = false;
bool yCollision = false;
bool zCollision = false;
//fishInput
unsigned int xOriginal = fishInput->getX();
unsigned int yOriginal = fishInput->getY();
unsigned int zOriginal = fishInput->getZ();
//fishInput2
unsigned int xEntity = fishInput2->getX();
unsigned int yEntity = fishInput2->getY();
unsigned int zEntity = fishInput2->getZ();
//directions, (triggerBox)
if (xOriginal - 1 == xEntity || xOriginal + 1 == xEntity || xOriginal == xEntity) { xCollision = true; }
if (yOriginal - 1 == yEntity || yOriginal + 1 == yEntity || yOriginal == yEntity) { yCollision = true; }
if (zOriginal - 1 == zEntity || zOriginal + 1 == zEntity || zOriginal == zEntity) { zCollision = true; }
//returns true if all 3 directions are true
if (xCollision && yCollision && zCollision) { collision = true; }
return collision;
}
int EntityControl::getYContainer() const
{
return _yContainer;
}
int EntityControl::getXContainer() const
{
return _xContainer;
}
int EntityControl::getZContainer() const
{
return _xContainer;
}
EntityControl::~EntityControl()
{
}
It worked before, don't know exactly what has changed. I think everything is declared like it should but this has been bothering me for a while. Putting the classes in another project and running it from there didn't work either. Neither did changing around some variables / removing methods, but again, I might have missed something.
The problem is that when you include EntityControl.h you have also included Fish.h which refers to Fish defined in Fish.h. However EntityControl.h refers to Fish.h which won't get included because of the pragma once directive. If you remove pragma once then you'd get an infinite loop because of circular dependency.
To solve the problem of circular dependencies use forward declarations.
Remove #include "EntityControl.h" from Fish.h and write class EntityControl; instead.
You may also remove #include "Fish.h"; from EntityControl.h and write class Fish; in its stead.

Class Not Declared in Scope

Getting a "throttle not declared in this scope" error when I attempt to compile the main.cpp. I am very new to c++, so bear with me. I have the #include "throttle.h" in the headers for both cpp files, so I am not sure why when i try to create a throttle object is is not declared...
main.cpp file:
#include <stdio.h>
#include "throttle.h"
using namespace std;
int main(int argc, char **argv)
{
throttle throt1(5, 0);
throttle throt2(4, 0);
return 0;
}
throttle.h file:
#ifndef MAIN_SAVITCH_THROTTLE
#define MAIN_SAVITCH_THROTTLE
namespace main_savitch_2A
{
class throttle
{
public:
// CONSTRUCTORS
//throttle( );
//throttle(int size);
throttle(int size = 1, int start = 0); //by adding this default
//constructor the other two
//are not needed
// MODIFICATION MEMBER FUNCTIONS
void shut_off( ) { position = 0; }
void shift(int amount);
// CONSTANT MEMBER FUNCTIONS
double flow( ) const
{
return position / double(top_position);
}
bool is_on( ) const
{
return (position > 0);
}
int get_top_position()const;
int get_position()const;
friend bool operator <(const throttle& throt1, const throttle& throt2);
//postcondtion: returns true if flow of throt1 < flow of throt2.
//return false if flow of throt1 > flow of throt2
private:
int top_position;
int position;
};
}
#endif
throttle.cpp file :
#include <cassert> // Provides assert
#include "throttle.h" // Provides the throttle class definition
using namespace std; // Allows all Standard Library items to be used
namespace main_savitch_2A
{
//throttle::throttle( )
//{ // A simple on-off throttle
//top_position = 1;
//position = 0;
//}
//throttle::throttle(int size)
// Library facilities used: cassert
//{
//assert(size > 0);
//top_position = size;
//position = 0;
//}
throttle::throttle(int size, int start)
{
assert(size > 0);
assert(start = 0);
top_position = size;
position = start;
}
void throttle::shift(int amount)
{
position += amount;
if (position < 0)
position = 0;
else if (position > top_position)
position = top_position;
}
bool operator <(const throttle& throt1, const throttle& throt2)
{
return(throt1.flow() < throt2.flow());
}
int throttle::get_top_position()const
{
return top_position;
}
int throttle::get_position()const
{
return position;
}
}
In your main, it should be main_savitch_2A::throttle throt1(5, 0);.
The same for throt2.
See namespaces for further details.