C++ Read/write data with user-define object - c++

I'm beginner with C++ and I have code like this
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;
class Role
{
public:
Role(int r, bool x)
:role(r), active(x)
{}
private:
int role;
bool active;
};
class Test
{
public:
Test(vector<Role> xxxx = {})
:xxx(xxxx)
{}
private:
std::vector<Role> xxx;
};
int main()
{
vector<Role> role = { Role(1,true),Role(2,false),Role(3, true) };
Test test1(role);
fstream dataTransfer("data.txt");
Test test2;
dataTransfer.write(reinterpret_cast<char*>(&test1), sizeof(Test));
dataTransfer.read(reinterpret_cast<char*>(&test2), sizeof(Test)); // error
return 0;
}
This code cause "Read access violation" but i can't find any error.
Thank for any help

Related

Using custom classes in different project as member of class C++ - ERROR

I am new to C++, and I am currently working on 2 different projects within the some solution in C++ with VSC and I am encountering the error "A class-qualified name is required"; I have created a custom class in a file inside a namespace like so in project Stock:
//in file Stock.h, project Stock
#pragma once
#include "CandleStick.h"
#include "StockRecord.h"
#include "MarketQue.h"
#include <string>
#include <vector>
namespace Stock {
class Stock {
private:
std::string s_stockID;
MarketQue* s_topCur;
StockRecord s_stockRecord;
std::vector<CandleStick> s_candleSticks;
unsigned int s_totalVol;
public:
Stock(const std::string&, MarketQue&, std::vector<unsigned int>&, unsigned int); //stockID, s_topCurPrice_B, s_topCurPrice_S, s_topCurVol_B, s_topCurVol_S, cs_interval, total_vol
void updateStock(int);
~Stock();
protected:
};
}
//in file Stock.cpp, project Stock
#include "Stock.h"
Stock::Stock::Stock(const std::string& stockID, MarketQue& topPrices, std::vector<unsigned int>& csInterval, unsigned int totalVol)
:s_stockID(stockID), s_topCur(&topPrices), s_stockRecord(StockRecord(topPrices.mq_size)), s_totalVol(totalVol) {
s_candleSticks.reserve(csInterval.size());
for (unsigned int i = 0; i < csInterval.size(); i++) {
s_candleSticks.emplace_back(topPrices.mq_topPrice_S[0], topPrices.mq_topPrice_B[0], csInterval[i]);
}
};
void Stock::Stock::updateStock(int totalVol) {
s_totalVol = totalVol;
s_stockRecord.updateStockRecord(*s_topCur);
for (unsigned int i = 0; i < s_candleSticks.size(); i++) {
s_candleSticks[i].updateCandleStick((s_topCur->mq_topPrice_B)[0], (s_topCur->mq_topPrice_S)[0]);
}
}
Stock::Stock::~Stock() {};
I have successfully linked the 2 projects together (I think, tested it in the main function with a file called App.cpp in project Market):
//in file App.cpp, project Market
#include "Stock.h"
#include "MarketQue.h"
#include <string>
#include <array>
#include <vector>
int main() {
//initializing
const std::string stockID = "001";
Stock::MarketQue topPrices(3);
std::vector<float> topCurPrice_B = { 3,2,1 };
std::vector<float> topCurPrice_S = { 4,5,6 };
topPrices.mq_topPrice_B = topCurPrice_B;
topPrices.mq_topPrice_S = topCurPrice_S;
std::vector<unsigned int> topCurVol_B = { 10,11,12 };
std::vector<unsigned int> topCurVol_S = { 13,14,15 };
topPrices.mq_topVol_B = topCurVol_B;
topPrices.mq_topVol_S = topCurVol_S;
std::vector<unsigned int> cs_Interval = { 100,300,1000 };
unsigned int totalVol= 3+2+1+4+5+6;
Stock::Stock first_stock(stockID, topPrices, cs_Interval, totalVol);
totalVol = 100;
first_stock.updateStock(totalVol);
//testing update
topCurPrice_B = { 13,12,11 };
topCurPrice_S = { 14,15,16 };
topCurVol_B = { 110,111,112 };
topCurVol_S = { 113,114,115 };
topPrices.mq_topPrice_B = topCurPrice_B;
topPrices.mq_topPrice_S = topCurPrice_S;
topPrices.mq_topVol_B = topCurVol_B;
topPrices.mq_topVol_S = topCurVol_S;
}
However, when I try to use this class(Stock::Stock) as a member inside of another class (in project Market), I received the error mentioned above ("A class qualified name is required");
I first did this:
//in file Market.h, project Market
#pragma once
#include "Stock.h"
#include <string>
#include <vector>
namespace Market {
class Market {
private:
std::string marketID;
std::vector<Stock::Stock> stock; //received error
Stock::Stock stock;
public:
Market();
void updateStock();
~Market();
protected:
};
}
At this point i figured it might be because of the namespace Market making it Market::Stock::Stock and i decided to remove the namespace Market:
//in file Market.h, in project Market
#pragma once
#include "Stock.h"
#include <string>
#include <vector>
class Market {
private:
std::string marketID;
std::vector<Stock::Stock> stock;
public:
Market();
void updateStock();
~Market();
protected:
};
I'd like to ask how to fix this problem, and if possible can someone explain to me what is happenning to the code that caused the error?
Thank you very much for your time.

Why is the Default Parameter being used each time? Initializing classes

When I printed the variables passed through, the default is printed first, followed by what I want passed. So the final result remains the same. The initialization is found in Owner.h and Owner.cpp. Variables are passed starting from the Dog.cpp. I've also tried changing my print statements to Dog.owner... but the result was the same.
Owner.h
#define OWNER_H
#include <iostream>
#include <string>
#include "Dog.h"
using namespace std;
class Owner {
private:
string name;
int age;
public:
Owner(string ownerName = "Lucy" , int ownerAge = 10); // default params
string getName();
int getAge();
};
#endif
Owner.cpp
#include <iostream>
#include <string>
#include "Dog.h"
using namespace std;
// Getters
string Owner::getName() {return name;}
int Owner::getAge() {return age;}
// Constructors
Owner::Owner(string ownerName, int ownerAge) :name(ownerName), age(ownerAge) {
Owner::getName();
Owner::getAge();
}
Dog.h
#ifndef DOG_H
#define DOG_H
#include <iostream>
#include <string>
#include "Owner.h"
using namespace std;
class Dog {
private:
string breed;
int age;
Owner owner;
static int dogCount;
public:
Dog();
Dog(string, int);
// Getter and Setter methods
void setBreed(string var);
void setAge(int var);
string getBreed();
int getAge();
// Other
void printDogInfo();
static int getDogCount() {return dogCount;}
};
#endif
Dog.cpp
#include <iostream>
#include <string>
#include "Dog.h"
#include "Owner.h"
using namespace std;
// Constructors
Dog::Dog(string ownerName, int ownerAge) {
Owner(ownerName, ownerAge);
dogCount++;
}
Dog::Dog() {
}
void Dog::printDogInfo() {
cout << "owner: " << owner.getName() << ", " << owner.getAge() << " yo" << endl << endl;
}
int main() {
Dog myDog1("Belle", 15);
myDog1.setBreed("Siberian Husky");
myDog1.setAge(2);
myDog1.printDogInfo();
return 0;
}
Dog::Dog(string ownerName, int ownerAge) {
Owner(ownerName, ownerAge);
dogCount++;
}
By:
Dog::Dog(string ownerName, int ownerAge) : Owner(ownerName, ownerAge) {
dogCount++;
}
Probably, you also want to fix this:
Owner::Owner(string ownerName, int ownerAge) :name(ownerName), age(ownerAge) {
// Owner::getName(); not needed
// Owner::getAge(); not needed
}
Dog::Dog(string ownerName, int ownerAge) {
Owner(ownerName, ownerAge);
dogCount++;
}
is equivalent to
Dog::Dog(string ownerName, int ownerAge) :
breed(),
owner()
{
Owner(ownerName, ownerAge); // Create temporary
dogCount++;
}
You probably want instead:
Dog::Dog(string ownerName, int ownerAge) :
breed(),
age(0),
owner(ownerName, ownerAge)
{
dogCount++;
}

No constructor for class C++ using class as java enum

i'm recently starting with c++ and I'm having troubles when I want to use a c++ class like Java's enums.
I would have the 'simulated enum' class attribute, but when I try to initialize the attribute in the constructor i received the following error:
no default constructor exists for model::suite
I now I have the constructor private, but the enum should have private constructors to prevent the construction of undefined objects of that class.
¿What should I do?
e.g.
suite.h
#include <iostream>
#include <string>
#include <vector>
namespace model
{
class Suite
{
public:
static const Suite CLUBS;
static const Suite DIAMONDS;
static const Suite SPADES;
static const Suite HEARTS;
static const int SIZE = 4;
private:
std::string name;
Suite(std::string name)
{
this->name = name;
}
public:
std::string toString()
{
return name;
}
std::vector<Suite> values()
{
return {Suite::CLUBS, Suite::DIAMONDS, Suite::SPADES, Suite::HEARTS};
}
};
const Suite Suite::CLUBS = Suite("CLUBS");
const Suite Suite::DIAMONDS = Suite("DIAMONDS");
const Suite Suite::SPADES = Suite("SPADES");
const Suite Suite::HEARTS = Suite("HEARTS");
}
card.h
#pragma once
#include <string>
#include "suite.h"
#include "face.h"
namespace model
{
class Card
{
public:
Card(int face, int suite);
Face getFace();
Suite getSuite();
bool isMergeable();
std::string toString();
private:
Face face;
Suite suite;
bool isRed();
bool isContigous(Card card);
};
}
card.cpp
#include <iostream>
#include "card.h"
using namespace std;
using namespace model;
Card::Card(int face, int suite)
{
this->face = Face::VALUES[face];
}
Face Card::getFace()
{
}
Suite Card::getSuite()
{
}
bool Card::isMergeable()
{
}
std::string Card::toString()
{
}
bool Card::isRed()
{
}
bool Card::isContigous(Card card)
{
}
Well finally I found a solution.
When we try to implement the 'simulated enum' on the cpp file, we have the this-> pointer and also the scope who envolves it (scope rules), so we need to define the object before the { } of the constructor.
#include <iostream>
#include "card.h"
using namespace std;
using namespace model;
Card::Card(Face face, Suite suite) : face(face), suite(suite)
{
}
That way we could implement a stronger and useful enums with attributes and methods.

No variable member function declared in class?

can sombody explain to me why my code will not work, and how to fix it thanks :)
I keep recieving this error :
no 'int burrito::setName()' member function declared in class 'burrito'
My goal is to call a function from a different class file
My main.cpp :
#include <iostream>
#include "burrito.h"
using namespace std;
int main()
{
burrito a;
a.setName("Ammar T.");
return 0;
}
My class header (burrito.h)
#ifndef BURRITO_H
#define BURRITO_H
class burrito
{
public:
burrito();
};
#endif // BURRITO_H
My class file (burrito.cpp):
#include "burrito.h"
#include <iostream>
using namespace std;
burrito::setName()
{
public:
void setName(string x){
name = x;
};
burrito::getName(){
string getName(){
return name;
};
}
burrito::variables(string name){
string name;
};
private:
string name;
};
Your code is a mess. You need to write function prototypes in the header file and function definitions in the cpp file. You are missing some basic coding structures. See below and learn this pattern of coding:
This code should work and enjoy burritos !
main():
#include <iostream>
#include "Header.h"
int main()
{
burrito a;
a.setName("Ammar T.");
std::cout << a.getName() << "\n";
getchar();
return 0;
}
CPP file:
#include "Header.h"
#include <string>
void burrito::setName(std::string x) { this->name = x; }
std::string burrito::getName() { return this->name; }
Header file:
#include <string>
class burrito
{
private:
std::string name;
public:
void setName(std::string);
std::string getName();
//variables(string name) {string name;} // What do you mean by this??
};
Your poor little burrito is confused. Confused burritos can't help much.
You may want your burrito declaration as:
class Burrito
{
public:
Burrito();
void set_name(const std::string& new_name);
std::string get_name() const;
private:
std::string name;
};
The methods could be defined in the source file as:
void
Burrito::set_name(const std::string& new_name)
{
name = new_name;
}
std::string
Burrito::get_name() const
{
return name;
}
The header file only has a constructor for the class. The member functions
setName(string) and getName()
are not declared in the header file and that is why you get the error.
Also, you need to specify the return type for functions.
One way to do this would be
//Header
//burrito.h
class burrito{
private:
string burrito_name;
public:
burrito();
string getName();
void setName(string);
}
//burrito.cpp
#include "burrito.h"
#include <iostream>
using namespace std;
string burrito::getName()
{
return burrito_name;
}
void burrito::setName(string bname)
{
bname =burrito_name;
}
This is a simple example for class in C++,
Save this in burrito.cpp file then compile and run it:
#include <iostream>
#include <string>
using namespace std;
class burrito {
public:
void setName(string s);
string getName();
private:
string name;
};
void burrito::setName(string s) {
name = s;
}
string burrito::getName() {
return name;
}
int main() {
burrito a;
a.setName("Ammar T.");
std::cout << a.getName() << "\n";
return 0;
}

Passing string as reference to function pointer c++

Below is my code
#include "stdafx.h"
#include <string.h>
#include <iostream.h>
using namespace std;
class ToDoCommands
{
public:
void getCommand(string);
};
void ToDoCommands::getCommand(string command)
{
cout<<command; //here i get ping
void (*CommandToCall)(void);
CommandToCall = command; // error here i want something like
// CommandToCall = ping
CommandToCall();
}
void ping(void)
{
cout<<"ping command executed";
}
int main()
{
ToDoCommands obj;
obj.getCommand("ping");
}
The function pointer should refer to function ping dynamically. A string same as function name is passed to getCommand function in main.
C++ just doesn't work that way. If you really need something like that, you'll have to make a table of functions that are indexed by name:
#include <assert.h>
#include <iostream>
#include <map>
#include <string>
using std::cout;
using std::string;
using std::map;
void ping(void)
{
cout << "ping command executed\n";
}
class ToDoCommands
{
public:
typedef void (*FunctionPtr)();
typedef string Name;
void registerFunction(Name name,FunctionPtr);
void callFunction(Name);
private:
map<Name,FunctionPtr> func_map;
};
void ToDoCommands::registerFunction(Name name,FunctionPtr func_ptr)
{
func_map[name] = func_ptr;
}
void ToDoCommands::callFunction(Name name)
{
assert(func_map.find(name)!=func_map.end());
func_map[name]();
}
int main(int argc,char **argv)
{
ToDoCommands to_do_commands;
to_do_commands.registerFunction("ping",ping);
to_do_commands.callFunction("ping");
return 0;
}
void ping(void)
{
// LL DD…DD XX
cout<<"ping command executed"<<endl;
}
class ToDoCommands
{
public:
void getCommand( void (*CommandToCall)(void)); //getCommand(ping)
};
void ToDoCommands::getCommand( void (*CommandToCall)(void) )
{
void (*CommandToCall1)(void);
CommandToCall1 = CommandToCall;
CommandToCall1();
}
int main()
{
ToDoCommands obj;
obj.getCommand( ping );
return 0;
}
i tried this and its working :)