Function not working when inside if or switch statements - oop

I need to solve a OOP problem in which I have to manage multiple classes inherited by each other. First I need to read all the data for all the Employees of a Company. The reading runs very well but I also need to display the read data after reading the command 1 (I need to use switch). I created a function "afisare_angajati()" which only works outside "if" and "switch" statements. I don't know why those statements disable my function. This happened to me before but I couldn't find the cause. Is something that I am not seeing? You can see my function at the end of the code. Thx for help.
#include<iostream>
#include<string>
#include<vector>
class Angajat{
protected:
std::string nume;
float salariu_baza;
std::string functie;
float procent_taxe_salariu;
public:
float get_salariu_net(){return 0;}
float get_salariu_brut(){return 0;}
std::string get_nume(){return 0;}
void marire_salariu(){}
Angajat(std::string nume,float salariu_baza,std::string functie,float procent_taxe_salariu=40):
nume(nume),salariu_baza(salariu_baza),functie(functie),procent_taxe_salariu(procent_taxe_salariu){}
void display(){
std::cout<<nume<<'\n';
std::cout<<functie<<'\n';
}
};
class Analist:public Angajat{
public:
Analist(std::string nume,float salariu_baza,std::string functie,float procent_taxe_salariu=40):
Angajat(nume,salariu_baza,functie,procent_taxe_salariu){}
};
class Programator:public Analist{
protected:
float procent_deducere_salariu_it;
public:
Programator(std::string nume,float salariu_baza,std::string functie,float procent_taxe_salariu=40):
Analist(nume,salariu_baza,functie,procent_taxe_salariu){}
};
class LiderEchipaProgramare:public Programator{
protected:
int vechime;
float bonus_vechime;
public:
LiderEchipaProgramare(std::string nume,float salariu_baza,std::string functie,int vechime,float procent_taxe_salariu=40):
Programator(nume,salariu_baza,functie,procent_taxe_salariu),vechime(vechime){
bonus_vechime=500;
}
};
class FirmaProgramare{
private:
std::vector<Angajat*> vec_ang;
public:
void afisare_angajati(){
for(Angajat* a:vec_ang){
a->display();
}
}
void mareste_salarii(float,float,float){}
void promoveaza(std::string){}
void adauga_angajat(Angajat* a){
vec_ang.push_back(a);
}
};
int main(){
std::string nume;
std::string functie;
float salariu_baza;
int vechime;
int nr_ang,comanda;
FirmaProgramare pula;
std::cin>>nr_ang;
for(int i=0;i<nr_ang;++i){
std::cin.ignore();
std::getline(std::cin,nume);
std::cin>>functie;
std::cin>>salariu_baza;
Angajat* p = nullptr;
if(functie=="Analist"){
p = new Analist(nume,salariu_baza,functie);
}
else{
if(functie=="Programator"){
p = new Programator(nume,salariu_baza,functie);
}
else{
p = new LiderEchipaProgramare(nume,salariu_baza,functie,vechime);
}
}
pula.adauga_angajat(p);
}
std::cin>>comanda;
//pula.afisare_angajati(); output is correct if I put the function outside of brackets
switch(comanda)
{
case 1:{
pula.afisare_angajati();
break;
}
}
}

Related

Arduino - passing values by reference from lamda to singleton

Hello i am bigginer in programing and i have specific problem.
I have been learning a new ways to write a code in small Arduino project.
that project have multiple objects like distance measuring Senzor, led diods , temperature senzor, etc. And all this objects have its own menu where you can, for example, start a calibration or just get values.
What i need is singleton class that has a function enter_esc() that need a int (*funct)() parameter basically function pointer.
That enter_esc(int (*funct)()) function just looping function until you press escape pin which is defined.
function Calibration() have inside some private: object data types like value or cali_value.
so i tried to insert function Calibration() right into enter_esc(Calibration) but it won't compile becouse i didnt pass that vlaues by reference or copy.
but what i found is lambda.
i made a lamda similar to a Calibration() function and i passed values by reference &{//domething;}
but i had to use enter_esc(std::function<int()>& funct) whitch is only int C++ standard library and not in Arduino C/C++ so my qestion is:
[is there some way how to pass values by reference by using lambda to a singleton class in Arduino ?]
(i konw it can be done differently but like i said i want to learn some new ways to program, also if you have some different way to make it i will by very happy to see it)
10Q for your time :)
//Class.h
#pragma once
class events {
private:
static events e_instance;
int p_menu, p_enter, p_esc, p_up, p_down;
int menuValue;
events();
public:
events(const events&) = delete;
static events& Get();
int ArrowUpDown(int maxVal);
int ArrowUpDown(int p_up, int p_down, int maxVal);
int enter_esc(const std::function<int()>& funct);
};
events events::e_instance;
class deviceBase : public Printables
{
public:
const char* a_pin;
int d_pin;
String type;
String deviceName;
bool inUse;
int actualCount;
public:
String getType() override;
int getActualCount() override;
String getName() override;
String getInUse() override;
};
class senzor : public deviceBase
{
private:
int Value;
int triggValue;
public:
int p_triggValue = 10;
static int allSenzors;
friend events;
senzor();
~senzor();
public:
int getValue();
int Calibration();
void changeTriggVal(int x);
void Reset();
void nullCalibration();
void Menu(int x);
void setName(String deviceName);
void setInUse(bool x);
int getPin();
};
int senzor::allSenzors = 0;
if you have some good advice to my code writing i will be also very glad
//Class.cpp
#include <iostream>
#include <string>
#include <functional>
#define LOG(x) std::cout << x << std::endl;
#define PINMENU 12
#define PINENTER 8
#define PINESC 9
#define PINUP 11
#define PINDOWN 13
using String = std::string;
struct Printables
{
virtual String getType() = 0;
virtual int getActualCount() = 0; ;
virtual String getName() = 0;
virtual String getInUse() = 0;
};
#include "Class.h"
events& events::Get() {
return e_instance;
}
int events::ArrowUpDown(int maxVal) {
if (maxVal) {
menuValue = menuValue < maxVal ? menuValue++ : menuValue;
}
if (maxVal) {
menuValue = menuValue > 0 ? menuValue-- : menuValue;
}
return menuValue;
}
int events::enter_esc(const std::function<int()>&funct) {
if (1) {
while (!p_esc) {
auto f = funct;
}
}
return 1;
}
int events::ArrowUpDown(int p_up, int p_down, int maxVal) { return 666; }
events::events() {};
String deviceBase::getType() { return type; }
int deviceBase::getActualCount() { return actualCount; }
String deviceBase::getName() { return deviceName; }
String deviceBase::getInUse() {
String Status;
Status = inUse == 1 ? "Active" : "Deactive";
return Status;
}
senzor::senzor() : Value(0), triggValue(1) {
a_pin = "xx";
type = "[SENZOR]";
deviceName = "[UNKNOWN]";
inUse = 0;
allSenzors++;
actualCount = allSenzors;
a_pin = 0;
}
senzor::~senzor() {
allSenzors = 0;
}
int senzor::getValue() {
Value = 4;
return Value;
}
int senzor::Calibration() {
triggValue = triggValue < getValue() ? getValue() : triggValue;
p_triggValue = triggValue;
return p_triggValue;
}
void senzor::changeTriggVal(int x) {
p_triggValue = x;
}
void senzor::Reset() {
p_triggValue = triggValue;
}
void senzor::nullCalibration() {
triggValue = 1;
}
void senzor::setName(String deviceName) {
this->deviceName = deviceName;
}
void senzor::setInUse(bool x) {
inUse = x;
}
int senzor::getPin() {
return 4;
}
int printsss() {
return 1;
}
////////////////////////////////this what i was writing about//////////////////////////////
void senzor::Menu(int x) {
events::Get().enter_esc([&]() { triggValue = triggValue < getValue() ? getValue() : triggValue;
p_triggValue = triggValue;
return p_triggValue; });
}
but if i use lambda in arduino with enter_esc(int (*funct)()) i get this kind of error
no matching function for call to 'events::enter_esc(senzor::Menu(int)::<lambda()>)'

System::String^ to TCHAR*

I have a class which collects all paths to .txt files of a given folder and stores them into a vector. Most of the functions I use require the usage of TCHAR* to get/set current directory and so on.
The class looks like this:
typedef std::basic_string<TCHAR> tstring;
class folderManager
{
private:
TCHAR searchTemplate[MAX_PATH];
TCHAR directory[MAX_PATH];
WIN32_FIND_DATA ffd;
HANDLE hFind;
vector<tstring> folderCatalog;
vector<tstring> fileNames;
bool succeeded;
public:
// get/set methods and so on...
};
// Changed TCHAR* dir to tstring dir
void folderManager::setDirectory(tstring dir)
{
HANDLE hFind = NULL;
succeeded = false;
folderCatalog.clear();
fileNames.clear();
// Added .c_str()
SetCurrentDirectory(dir.c_str());
GetCurrentDirectoryW(MAX_PATH, directory);
TCHAR fullName[MAX_PATH];
StringCchCat(directory, MAX_PATH, L"\\");
StringCchCopy(searchTemplate, MAX_PATH, directory);
StringCchCat(searchTemplate, MAX_PATH, L"*.txt");
hFind = FindFirstFile(searchTemplate, &ffd);
if (GetLastError() == ERROR_FILE_NOT_FOUND)
{
FindClose(hFind);
return;
}
do
{
StringCchCopy(fullName, MAX_PATH, directory);
StringCchCat(fullName, MAX_PATH, ffd.cFileName);
folderCatalog.push_back(fullName);
fileNames.push_back(ffd.cFileName);
}
while (FindNextFile(hFind, &ffd) != 0);
FindClose(hFind);
succeeded = true;
}
This is where I need to do the conversion of System::String^ to TCHAR*
private: System::Void dienuFolderisToolStripMenuItem_Click(System::Object^
sender, System::EventArgs^ e)
{
FolderBrowserDialog^ dialog;
dialog = gcnew System::Windows::Forms::FolderBrowserDialog;
System::Windows::Forms::DialogResult result = dialog->ShowDialog();
if (result == System::Windows::Forms::DialogResult::OK)
{
// Conversion is now working.
tstring path = marshal_as<tstring>(dialog->SelectedPath);
folder->setDirectory(path);
}
}
marsha_as "Performs the marshaling on a specific data object to convert it between a managed and a native data type".
Here there is the table for possible type conversion.
I use it this way:
marshal_as<std::wstring>(value)
TCHAR can be char or wchar_t, both of them present in marshal_as specialization, I suppose you need to point TCHAR* as template parameter:
TCHAR* result = marshal_as<TCHAR*>(value)
Actually MSDN says that you have to use it this way:
#include <msclr\marshal.h>
using namespace System;
using namespace msclr::interop;
int main(array<System::String ^> ^args)
{
System::String^ managedString = gcnew System::String("Hello World!!!");
marshal_context ^ context = gcnew marshal_context();
const wchar_t* nativeString = context->marshal_as<const wchar_t*>(managedString);
//use nativeString
delete context;
return 0;
}

How do I setup Using Systems::IO::Ports in DLL so that it can be called from a loadlibrary function

Using vc2012 express c++
I am a little confused on how a runtime library works, but I had needed to create one for a driver from some hardware I have so that it can be used in a SDK.
My source code is as follows
#include "PhantomAdapter.h"
#include <stdexcept>
int ready()
{
//return Comms::SerialPort::check();
return 1;
}
int open()
{
int flag=0;
//flag=Comms::SerialPort::openPort();
return flag;
}
int close()
{
Comms::SerialPort::closePort();
return 1;
}
int angle(double& angle)
{
angle = Comms::SerialPort::read();
return 0;
}
int torque(double torque)
{
Comms::SerialPort::send((Byte)torque);
return 1;
}
namespace Comms
{
//static p1 = gcnew System::IO::Ports::SerialPort();
int SerialPort::openPort()
{
bool check=0;
p1 = gcnew System::IO::Ports::SerialPort();
p1->BaudRate = 57600;
p1->PortName = "COM3";
if(p1->IsOpen)
return 0;
else {
p1->Open();
return 1;
}
}
int SerialPort::check()
{
array<String^>^ serialPorts = nullptr;
bool flag = true;
serialPorts = p1->GetPortNames();
for each(String^ port in serialPorts)
{
if(port=="COM3")
flag= true;
}
return flag;
}
void SerialPort::closePort()
{
p1->Close();
}
void SerialPort::send(Byte data)
{
array<unsigned char>^ buffer = gcnew array<Byte>(1);
buffer[0] = (char)data;
p1->Write(buffer,0,1);
}
double SerialPort::read()
{
double data;
data = p1->ReadByte();
return data;
}
}
header
#define PHANTOMADAPTER_API __declspec(dllexport)
#else
#define PHANTOMADAPTER_API __declspec(dllexport)
#endif
#using <mscorlib.dll>
#using <system.dll>
using namespace System;
using namespace System::IO::Ports;
using namespace System::Threading;
extern "C" {
PHANTOMADAPTER_API int ready();
PHANTOMADAPTER_API int open();
PHANTOMADAPTER_API int close();
PHANTOMADAPTER_API int angle(double& angle);
PHANTOMADAPTER_API int torque(double torque);
}
namespace Comms
{
public ref class SerialPort
{
private:
static System::IO::Ports::SerialPort^ p1;
public:
static int openPort();
static void closePort();
static double read();
static void send(Byte data);
static int check();
};
}
I am getting the following error when I call the angle DLL function or any function that requires the Comms namespace.
System.NullReferenceException: Object reference not set to an instance of an object.
at System.IO.Ports.SerialPort.get_IsOpen()
at System.IO.Ports.SerialPort.ReadByte()
at angle(Double* angle)
can someone please point me in the right direction, I feel as if the serialPort class can't be open from runtime library unless I import it somehow

Adressing variable using a string and an int in Arduino

I wonder how I can address a variable by putting together a string and an int in Arduino.
I´m using many variables of the same type and with almost the same name. I´m just append a number to each variable.
The names of the variables are e.g. int sensorValue_1; int sensorValue_2; and so on.
I´d like to write less because my code is becoming too long.
When addressing the variables, I´d like to write something like this: sensorValue_[+ intVariable];
Here is an example of what I mean:
int sensorIndex_1 = 1;
int sensorIndex_2 = 2;
int sensorIndex_3 = 3;
int sensorValue_1;
int sensorValue_2;
int sensorValue_3;
void setup()
{
Serial.begin(9600);
}
void loop()
{
doSomething(sensorIndex_1);
//doSomething(sensorIndex_2);
//doSomething(sensorIndex_3);
}
void doSomething(int sensorIndex)
{
if(sensorIndex == 1)
{
Serial.print("Sensor 1: ");
sensorValue_1 = analogRead(A1);
Serial.println(sensorValue_1);
}
if(sensorIndex == 2)
{
Serial.print("Sensor 2: ");
sensorValue_2 = analogRead(A2);
Serial.println(sensorValue_2);
}
if(sensorIndex == 3)
{
Serial.print("Sensor 3: ");
sensorValue_3 = analogRead(A3);
Serial.println(sensorValue_3);
}
delay(1000);
}
And I want to shorten the code in the doSomething() method.
I want to have something like this:
Notice the "[+ sensorIndex]"
void doSomething(int sensorIndex)
{
Serial.print("Sensor [+ sensorIndex]: ");
sensorValue_[+ sensorIndex] = analogRead(A[+ sensorIndex]);
Serial.println(sensorValue_[+ sensorIndex]);
delay(1000);
}
By the way: I´d like to avoid for-loops, if possible.
In my case, the code would become too complicated.
How do I manage this?
User2461391 has a great start but the rest of the puzzle I think you want is:
int array1[3];
int array2[3];
int arrayx[3];
void setup()
{
}
void loop()
{
int index=1;
array1[2]=doSomething(2);
arrayx[index]=doSomething(index);
Serial.print("Sensor ");
Serial.print(index);
Serial.print(": ");
Serial.println(arrayx[index]);
while(1);
}
int doSomething(int sensorIndex) // It probably makes more sense to return the value
{
return (analogRead(sensorIndex));
}
You don't need to use A1 and A2 and the likes to define the analog pin you want to read. Just 1 or 2 will do.
void doSomething(int sensorIndex)
{
Serial.print("Sensor ");
Serial.print(sensorIndex);
Serial.print(": ");
sensorValue = analogRead(sensorIndex);
Serial.println(sensorValue);
delay(1000);
}

Is there an equivalent to __attribute__((ns_returns_retained)) for a malloc'd pointer?

I'm looking for an annotation something like
-(SomeStruct *) structFromInternals __attribute__((returns_malloced_ptr))
{
SomeStruct *ret = malloc(sizeof(SomeStruct));
//do stuff
return ret;
}
to soothe the clang static analyzer beasts.
The only viable attributes link I can find is for GCC, but it doesn't even include ns_returns_retained, which is in an extension, I assume.
EDIT:
as to why this is needed, I have a scenario that I can't repro in a simple case, so it may have to do with a c lib in an Objective-C project... The gist is, I get a static analyzer warning that the malloc in createStruct is leaked:
typedef struct{
void * data;
size_t len;
}MyStruct;
void destroyStruct(MyStruct * s)
{
if (s && s->data) {
free(s->data);
}
if (s) {
free(s);
}
}
MyStruct * createStructNoCopy(size_t len, void * data)
{
MyStruct * retStruct = malloc(sizeof(MyStruct));
retStruct->len = len;
retStruct->data = data;
return retStruct;
}
MyStruct * createStruct(size_t len, void * data)
{
char * tmpData = malloc(len);
memcpy(tmpData, data, len);
return createStructNoCopy(len, tmpData);
}
MyStruct * copyStruct(MyStruct * s)
{
return createStruct(s->len, s->data);
}
The function annotation ownership_returns(malloc) will tell the Clang static analyser that the function returns a pointer that should be passed to free() at some point (or a function with ownership_takes(malloc, ...)). For example:
void __attribute((ownership_returns(malloc))) *my_malloc(size_t);
void __attribute((ownership_takes(malloc, 1))) my_free(void *);
...
void af1() {
int *p = my_malloc(1);
return; // expected-warning{{Potential leak of memory pointed to by}}
}
void af2() {
int *p = my_malloc(1);
my_free(p);
return; // no-warning
}
(See the malloc-annotations.c test file for some more examples of their use.)
At the moment, these annotations only take effect when the alpha.unix.MallocWithAnnotations checker is run (which is not run by default). If you're using Xcode, you'll need to add -Xclang -analyzer-checker=alpha.unix.MallocWithAnnotations to your build flags.