I am really stuck at this problem for two days now. I know I am missing some crutial information but I don't know what.
I am programming an ESP32 using vscode and platformio.
I have imported ezButton and ezOutput. They both work fine when I call them from main.cpp. I assume this is because I am not calling them from inside a different class. Now I wrote a custom class which does some stuff and I want to read inputs from ezButton and write outputs to ezOutput.
Where my head is stuck at at this point is that I don't now how to correctly initialize the classes correctly.
I imagine it working like in my main.cpp where I for example just type inputPinName.isPressed();and I get my information. This should also work the other way like outputPinName.high();.
I would really appreciate someone explaining this to me or providing a link to a resource that explains this issue.
Here are some code snippets:
main.cpp
#include <ezButton.h>
#include <ezOutput.h>
// INPUTS
ezButton inputPinUp(34, INPUT_PULLDOWN);
//... same for all other inputs
// OUTPUTS
ezOutput outputPinUp(4);
ezOutput outputPinDown(0);
#define DEBOUNCE_TIME 50
void setup()
{
inputPinUp.setDebounceTime(DEBOUNCE_TIME);
//... same for all other pins
}
void loop()
{
inputPinUp.loop();
//... same for all other pins
}
shutter.h
#include <ezButton.h>
#include <ezOutput.h>
class shutter
{
private:
int inputPinUp;
//...
int _outUp;
int _outDown;
ezButton Button_;
ezOutput Output_;
public:
shutter(ezOutput& outputPin) : Output_(outputPin) {} //ERROR: no default constructor exists for class "ezButton"
shutter(ezButton& Pin) : Button_(Pin) {} //ERROR: no default constructor exists for class "ezOutput"
void shutterInput(
int inputPinUp,...);
void shutterOutput(
int outputPinUp,
int outputPinDown);
void stop(void);
void driveUp(void);
void driveDown(void);
};
I didn't switch the error messages above. They are actually reversed somehow.
shutter.cpp
#include "shutter.h"
//...
void shutter::shutterOutput(
int outputPinUp,
int outputPinDown)
{
int _outUp = outputPinUp; //I am not sure if I even have to do this
}
void shutter::stop(void)
{
ezOutput _outUp.low(); //ERROR: no default constructor exists for class "ezOutput"
digitalWrite(_outDown, LOW);
_moving = false;
}
Related
It seems that, when I pass an class it is not passing a persistant (the same) instance of that class as I would expect. I'm assuming this has something to do with memory state but I would appreciate it if someone could explain exactly what is happening. The issue is easily demonstrated as follows :
Main.ino
#include "Debug.h"
#include "Box.h"
Debug debug;
Box box(debug);
void loop(){
debug.message("loop");
debug.line();
}
void setup(){
debug.init();
box.init();
debug.message("Setup Complete");
debug.line();
}
Debug.h
#ifndef DEBUG_H
#define DEBUG_H
class Debug {
private:
bool state;
public:
Debug();
void init();
void message(const char *str);
void message(int);
void line();
};
#endif
Debug.cpp
#include "Debug.h"
#include <Arduino.h>
Debug::Debug() : state(false) {}
void Debug::init() {
if (state == false){
Serial.begin(9600);
state = true;
}
}
void Debug::message(const char *messageChar) {
if (state){
const char *p;
p = messageChar;
while (*p) {
Serial.print(*p);
p++;
}
}
}
void Debug::message(int messageInt) {
if (state){
Serial.print(messageInt);
}
}
void Debug::line() {
if (state){
Serial.println();
}
}
Box.h
#ifndef BOX_H
#define BOX_H
#include "Debug.h"
class Box {
private:
Debug debug;
public:
Box(Debug &debug);
void init();
};
#endif
Box.cpp
#include "Box.h"
#include <Arduino.h>
Box::Box(Debug &debug):
debug(debug)
{}
void Box::init(){
// Switches
pinMode(28, INPUT_PULLUP);
debug.message("Box intialized");
debug.line();
}
So the above code outputs to serial:
Setup Complete
If I modify Box::init() to
void Box::init(){
// Switches
pinMode(28, INPUT_PULLUP);
debug.init();
debug.message("Box intialized");
debug.line();
}
I get what I want :
Box initialized
Setup Complete
If I get rid of Box constructor class and instead do
void Box::init(Debug &debug){
this->debug = debug;
// Switches
pinMode(28, INPUT_PULLUP);
debug.message("Box intialized");
debug.line();
}
Called via Main.ino like
void setup(){
debug.init();
box.init(debug);
debug.message("Setup Complete");
debug.line();
}
I get the desired response again. I don't understand why my first attempt doesn't work nor do I feel comfortable knowing what best practices are. I would appreciate any guidance.
You have two Debug values in your code. One global, one member of the Box class.
Those are two distinct values, since Box create or copy from a value to create its own, and there's the global one.
A solution would be to contain a reference or a pointer.
Here's the example with a reference:
class Box {
private:
Debug& debug;
// ^---- there
public:
Box(Debug &debug);
void init();
};
If you want Box to still be assignable, then use a pointer:
class Box {
private:
Debug* debug;
// ^---- now it's a star
public:
Box(Debug &debug);
void init();
};
Box::Box(Debug &debug):
debug(&debug)
{} // ^----- here, we take the address of the debug variable.
Since references are immutable, you loose some important feature of the language: assignment.
struct thing {
int& ref;
};
int main () {
int a, b;
thing t1{a}, t2{b};
t1 = t2; // ERROR!
}
The assignment would cause t1.ref to point to b after the assignment.
Pointer has a more difficult syntax and hard to guess semantics. However, they play very well with assignment since they give you more freedom:
struct thing {
int* ptr;
};
int main () {
int a, b;
thing t1{&a}, t2{&b};
t1 = t2; // Works, t1.ptr points to b
}
I am just starting an assignment and am beginning with defining the functions of the class in the "Distance.h" tab and although I am pretty sure my functions are initialized correctly, I am still getting compiler errors saying that "definition not found." I used an online tutor and he ran it on his computer and did not get any errors, although he was not any further help with me fixing this issue. Does anyone know what I am supposed to do in this situation as this is my only computer or if anyone can tell me if I actually am just coding wrong.
Here is my "Distance.h":
#pragma once
class Distance
{
private:
long length;
public:
// Transformers
void setLength(long newLength);
void setFeet(int newFeet);
// Observors
long getLength();
int getFeet();
int getInches();
double getLengthInFeet();
};
You have to define your class methods. For instance:
#pragma once
class Distance
{
private:
long length;
public:
//Transformers
void setLength(long newLength){
// TODO: define your method here
// For instance: length = newLength;
}
void setFeet(int newFeet){
// TODO: define your method here
}
//Observors
long getLength(){
// TODO: define your method here
}
int getFeet(){
// TODO: define your method here
}
int getInches(){
// TODO: define your method here
}
double getLengthInFeet(){
// TODO: define your method here
}
};
Well, hi there.
I'm new to c++ and I'm having some issues that I'm not sure what is causing them.
This is my main:
#include "GameWindow.h"
int main(void)
{
GameWindow * game_window = new GameWindow(true);
/* loop the game */
while (game_window->GetRunning())
{
// update
game_window->Update();
// draw
game_window->Draw();
}
delete game_window;
return 0;
}
and this is my header:
class GameWindow
{
private:
bool _running;
//GLFWwindow* _window;
public:
void SetRunning(bool new_val);
bool GetRunning();
GameWindow(bool running);
void Draw();
void Update();
}
and my c++ file:
#include "GameWindow.h"
void GameWindow::SetRunning(bool new_val)
{
_running = new_val;
}
bool GameWindow::GetRunning()
{
return _running;
}
GameWindow::GameWindow(bool running) :
_running(running)
{
}
void GameWindow::Draw()
{
}
void GameWindow::Update()
{
}
While going through all of this I find it tough to find why Visual Studio refuse to compile this code.
It's raising errors about how 'SetRunning' is overloading a function which differs only in return values, and that the return type of main should be Int and not GameWindow, and with all of this I just went completely lost.
Tried to put 'SetRunning' as a comment to simplify the issue but instead it raised the same on 'GetRunning' instead.
I'm guessing it's a really stupid mistake that is easy to fix, but still, can't find it.
Thank you for your time, and I'll appreciate any kind of help.
Missing ; at the end of class definition.
class GameWindow
{
// .....
}; // Missing semi-colon
Missing ; in class defination
{
};
because of this when you include the file in program then compiler not found the end of the class hence it says return type of main should be int not GameWindow
Before I present the code which is found at the bottom of this post I would like to talk about the issue and the fix's that I do not desire. Okay basically I've created a GUI from scratch sort of and one requirement I wanted for this was allow components to have their own click executions so if i click a button or tab etc.. It would call Component->Execute(); Well normally you would do something like a switch statement of ids and if that components ID equaled n number then it would perform this action. Well that seemed kinda dumb to me and I thought there has to be a better way. I eventually tried to incorporate a feature in JAVA where you would do like Component.AddActionListener(new ActionListener( public void execute(ActionEvent ae) { })); or something like that and I thought that this feature has to be possible in C++. I eventually came across storing void functions into a variable in which could be executed at any time and modified at any time. However I hadn't noticed an issue and that was this only worked with static functions. So below you'll see my problem. I've patched the problem by using a pointer to SomeClass however this would mean having an individual function call for every class type is there no way to store a function callback to a non-static class member without doing the below strategy? and instead doing a strategy like the commented out code?
//Main.cpp
#include <iostream> //system requires this.
#include "SomeClass.h"
void DoSomething1(void)
{
std::cout << "We Called Static DoSomething1\n";
}
void DoSomething2(void)
{
std::cout << "We Called Static DoSomething2\n";
}
int main()
{
void (*function_call2)(SomeClass*);
void (*function_call)() = DoSomething1; //This works No Problems!
function_call(); //Will Call the DoSomething1(void);
function_call = DoSomething2; //This works No Problems!
function_call(); //Will Call the DoSomething2(void);
SomeClass *some = new SomeClass(); //Create a SomeClass pointer;
function_call = SomeClass::DoSomething3; //Static SomeClass::DoSomething3();
function_call(); //Will Call the SomeClass::DoSomething3(void);
//function_call = some->DoSomething4; //Non-Static SomeClass::DoSomething4 gives an error.
//function_call(); //Not used because of error above.
function_call2 = SomeClass::DoSomething5; //Store the SomeClass::DoSomething(SomeClass* some);
function_call2(some); //Call out SomeClass::DoSomething5 which calls on SomeClass::DoSomething4's non static member.
system("pause");
return 0;
}
//SomeClass.hpp
#pragma once
#include <iostream>
class SomeClass
{
public:
SomeClass();
~SomeClass();
public:
static void DoSomething3(void);
void DoSomething4(void);
static void DoSomething5(SomeClass* some);
};
//SomeClass.cpp
#include "SomeClass.h"
SomeClass::SomeClass(void)
{
}
SomeClass::~SomeClass(void)
{
}
void SomeClass::DoSomething3(void)
{
std::cout << "We Called Static DoSomething3\n";
}
void SomeClass::DoSomething4(void)
{
std::cout << "We Called Non-Static DoSomething4\n";
}
void SomeClass::DoSomething5(SomeClass *some)
{
some->DoSomething4();
}
Secondary Fix for what I'll do not an exact answer I wanted but it meets my needs for now along with allowing additional features which would have become overly complicate had this not existed.
//Component.hpp
#pragma once
#include <iostream>
#include <windows.h>
#include <d3dx9.h>
#include <d3d9.h>
#include "Constants.hpp"
#include "ScreenState.hpp"
#include "ComponentType.hpp"
using namespace std;
class Component
{
static void EMPTY(void) { }
static void EMPTY(int i) { }
public:
Component(void)
{
callback = EMPTY;
callback2 = EMPTY;
callback_id = -1;
}
Component* SetFunction(void (*callback)())
{
this->callback = callback;
return this;
}
Component* SetFunction(void (*callback2)(int), int id)
{
this->callback_id = id;
this->callback2 = callback2;
return this;
}
void execute(void)
{
callback();
callback2(callback_id);
}
}
The syntax for pointers-to-member-functions is as follows:
struct Foo
{
void bar(int, int);
void zip(int, int);
};
Foo x;
void (Foo::*p)(int, int) = &Foo::bar; // pointer
(x.*p)(1, 2); // invocation
p = &Foo::zip;
(x.*p)(3, 4); // invocation
Mind the additional parentheses in the function invocation, which is needed to get the correct operator precedence. The member-dereference operator is .* (and there's also ->* from an instance pointer).
I'm new to C++ and trying to code a HashTable data structure.
I've written it to be generic using templates, and I've included a HashEntry object to use in it to allow for easy quadratic probing for collisions.
The code I have is:
(in a .C file that #include's the below class definition .H file):
HashEntry::HashEntry()
{
this->isActive = false;
}
And the associated .H file with the class definitions is:
#include <iostream>
#include <string>
#include "Entry.C"
using namespace std;
#define Default_Size 50000
class HashEntry;
template <class T> class HashTable
{
private:
int size;
int occupied;
T array[Default_Size];
public:
HashTable();
int Size();
void Add(T t);
void DebugAdd(T t, int index);
T* Get(string index);
/* How do I declare the existence of HashEntry BEFORE here? */
int FindNextOpen(HashEntry he); // Only works for hash_entry objects!
int Hash(string str);
void Rehash();
};
class HashEntry
{
private:
Entry e;
bool isActive;
public:
HashEntry();
HashEntry(Entry e);
bool IsActive();
Entry GetEntry();
};
Whenever I try and compile everything, I get the error for the HashEntry constructor above:
"no matching function for call to Entry::Entry()" ... "candidates are.....".
I have no idea what it means -- when I try to include a default Entry() constructor (my first interpretation), it throws more errors.
Thanks for the help!
UPDATE -- ENTRY.C:
#include "Entry.H"
/* ***Entry Methods*** */
/*
* Overloaded Entry obejct constructor that provides a string value.
*/
Entry::Entry(string s)
{
this->value = s;
this->count = 0;
}
/*
* Returns the number of times this Entry has been accessed/
* found.
*/
int Entry::Count()
{ return this->count; }
/*
* Returns the string value stored in the Entry object.
*/
string Entry::Value()
{ return this->value; }
And the associated .H file with the class definitions is:
#include <iostream>
#include <string>
#include "Entry.C"
Whoa! Never, ever #include a source file in a header.
Your Entry.C should not exist. Instead define the constructor in your header, inside the class definition:
class HashEntry
{
private:
Entry e;
bool isActive;
public:
HashEntry() : isActive(true) {}
...
}
One thing that you haven't shown us is the definition of the class Entry. That is one of the sources of your problem. It's a bit hard to pin down your problem when you didn't show us the very thing that is causing it.
I found the problem.
The error message says there is not matching function call for "Entry::Entry()". Because in no case was I actually creating Entry objects I had no idea what it meant.
I tried adding an explicit default constructor for class Entry and it resolved.
Thanks for the help everyone!