I'm new to C++ and I have no idea why I can't send parking as a parameter. It's the first time I use struct, so maybe I'm forgetting something. I've tried sending the adress to parking but I get an error.
const int MAX_TAB = 10;
struct bike
{
int Number;
string Type;
};
bike ReadFile(bike parking[]);
int void main()
{
bike parking[MAX_TAB];
ReadFile(parking[MAX_TAB]); // This line is incorrect
}
bike ReadFile(bike parking[])
{
...
return parking[MAX_TAB];
}
Why does this not work? And how can I make it works?
Thanks you
I have no idea why I can't send parking as a parameter.
You can't do this because parking array decays to pointer, and it doesn't take the size of the array.
ReadFile(parking[MAX_TAB]); // MAX_TAB is not taken as input param
Instead you should do this:
bike ReadFile(bike parking[], size_t size);
and to call that function:
ReadFile(parking, MAX_TAB);
When passing arrays, don't add [].
Compiled using C++14 on CPP.SH
// dependecies
#include <iostream>
#include <string>
#include <fstream>
// namespace for string
using std::string;
// defined max tab for array
const int MAX_TAB = 50;
// structure definition
struct bike
{
int Number;
string Type;
string Test;
int Km;
int Stage;
};
// ReadFile(...) signature
bike ReadFile(bike *, size_t);
int main()
{
bike parking[MAX_TAB]; //instantiate array of bike object
ReadFile(parking, MAX_TAB); //only pass the array itself, not the array[
}
// parameters are array* and size
bike ReadFile(bike parking[], size_t size)
{
return *parking; //reference the array
}
Related
I am new to c++ & don't know the basics all that well. pls help (sorry if the solution to this is already available, but I couldn't find any)
This is the Error I am getting:
expected primary-expression before ‘]’ token
char CusName[50]=x[];
^
For this code below:
#include <iostream>
using namespace std;
class BankAccount
{
private:
char CusName[50];
char CusId[10];
float accBalance, dep, witd;
public:
void setCusDetails(char x[], char n)
{
char CusName[50]=x[];
}
};
int main()
{
BankAccount customer1;
char cus1Name[50];
cin>>cus1Name;
customer1.setCusDetails(cus1Name, 50);
return 0;
}
Your char array looks like a string. Try using std::string instead and prefer using const references for function parameters.
If you want to use char arrays, and if your point was to copy a null-terminated string by value, then use functions like strncpy.
Using std::string may be easier for you to hide the burden of memory allocation and discover the language step by step.
You can instead use string to input and pass values.
#include <iostream>
using namespace std;
class BankAccount
{
private:
string CusName; //CusName of type string
char CusId[10];
float accBalance, dep, witd;
public:
void setCusDetails(string str, char n) //parameter str of type string
{
CusName=str; //Assign it to the already declared 'CusName' variable.
}
};
int main()
{
BankAccount customer1;
string cus1Name;
cin>>cus1Name;
customer1.setCusDetails(cus1Name, 50);
return 0;
}
I'm getting no matching function for call to error how can I fix this without using vectors.
This is my header, I'm getting the error at fList method part in cpp.
class Flight{
public:
Flight(int fly,int rw,int st);
~Flight();
Flight* fList(int& sizeOfArray);
private:
int FlightNumber;
int row;
int seat;
int* flightArray;
};
This is my cpp:
#include <iostream>
#include <string>
using namespace std;
#include "Flight.h"
Flight::Flight(int fly,int rw,int st){
FlightNumber = fly;
row = rw;
seat = st;
}
Flight::~Flight(){};
Flight* Flight::fList(int& sizeOfArray){
flightArray = new Flight[sizeOfArray];
return flightArray;
}
So
int* flightArray;
should be
Flight* flightArray;
Your code is allocating an array of Flights but your variable is declared for integers not Flights.
Plus as pointed out by #MikeCAT you need to default constructor for Flight if you are going to allocate them with new[].
I have created an array dynamically of structures and now i am willing to pass it to function.What is the correct method of doing it?What should i put in parameter of function in MAIN for doing it?
void function(Data *family)
{
//code
}
int main()
{
struct Data{
string name;
int age;
string dob;
};
Data *family = new Data[3];
function(Data); //ERROR in parameter i guess!
}
It is better to use more safe ways using std::vector or std::shared_ptr. Because it is easy to make a mistake when you use raw pointers.
If you really need to use raw pointer than you need fix your code:
#include <string>
#include <iostream>
// "Data" should be declared before declaration of "function" where "Data" is used as parameter
struct Data {
std::string name;
int age;
std::string dob;
};
void function(Data *family)
{
std::cout << "function called\n";
}
int main()
{
Data *family = new Data[3];
// fill all variables of array by valid data
function(family); // Pass variable "family" but not a type "Data"
delete[] family; // DON'T FORGET TO FREE RESOURCES
return 0; // Return a code to operating system according to program state
}
Every c++ programmer needs to learn std::vector, which is a dynamic array:
#include <vector>
struct Data{
string name;
int age;
string dob;
};
void function(const std::vector<Data>& family)
{
//code
}
int main()
{
auto family = std::vector<Data>(3);//family now contains 3 default constructed Data
function(family);
}
Not sure what actually what actually you are looking for, I guess you can try like this:
First define your structure outside from main so it would be accessible as function parameter. Then instead of Data pass object family to the function.
struct Data {
string name;
int age;
string dob;
};
void function(Data *family)
{
//code
}
int main()
{
Data *family = new Data[3];
function(family);
}
im new in c++ (and not to old in programming...) and i have problem with handling vectors and strucs in class.
basically i have a vector and a array of pointers to struct members in the class and i want work on the in my methos but im doing something worng/
here is my movement.h
#pragma once
using namespace std;
class movement
{
private:
static const int MAX_ROW_PER_TRACKER = 100;
static const int MIN_TO_START_CALC = 30;
static const int MAX_TRACKERS = 20;
struct tracker
{
int id;
double a[MAX_ROW_PER_TRACKER];
double b[MAX_ROW_PER_TRACKER];
double c;
};
vector<int> trackersOrder[MAX_TRACKERS] = {};
tracker* trackersArr[MAX_TRACKERS];
public:
movement();
void addRow(int a, int b, int c);
~movement();
};
and my movement.cpp
#include "stdafx.h"
#include "movement.h"
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
movement::movement()
{
}
void movement::addRow(int id, int a, int b)
{
int index;
vector<int>::iterator searchID = find(trackersOrder.begin(), trackersOrder.end(), ID);
if (searchID == trackersOrder.end())
{
vector<int>::iterator freeLocation = find(trackersOrder.begin(), trackersOrder.end(), 0);
index = freeLocation - trackersOrder.begin();
trackersOrder.insert(trackersOrder.begin + index, id);
structArr[index] = new tracker;
structArr[index]->id = id;
structArr[index]->a[0] = a;
structArr[index]->b[0] = b;
structArr[index]->c = 0;
}
}
movement::~movement()
{
}
so when i send to method "addRow" id, and b i want to first check if i allready have this id in my vector (the vector just give me the index for the structs array) and if not then if put the id in the first empty place in the vector and on the structs array/
but from some reasin its look to me that the methid dont reconized the vector and the structs. can you help me understand why?
p.s - i can bet that i have more mistakes in my code, its my firs try with pointers and ect. (im comming from the good life in Matlab) so i will be happy to learn on them also
thank you very much!
The main problem
The problem is that in your code, trackersOrder is not a vector but an array of vectors:
vector<int> trackersOrder[MAX_TRACKERS] = {}; // array of MAXTRACKERS vectors !!
The solution
If you define it as simple vector, it should work better:
vector<int> trackersOrder;
If you want to set its size do it in the movement constructor:
movement::movement() : trackersOrder(MAX_TRACKERS)
{
}
Other issues
There is a case typo with an ID that should be id.
auto searchID = find(trackersOrder.begin(), trackersOrder.end(), id); // by the way auto is easier + ID corrected
There are a missing () after a begin whicn transforms unfortunately your iterator arithmetic into function pointer arithmetic (sic!!):
trackersOrder.insert(trackersOrder.begin() + index, id); // corrected
Finally, there are a couple of structArr that should be replaced by trackersArr.
The result does finally compile (online demo)
I am trying to learn C++ OOP and I made the follwing code:
main.cpp
#include <iostream>
#include <string>
#include "monster.h"
using namespace std;
int main(int argc, char** argv) {
Monster monster("Wizard",150,50);
Monster monster2("Gorgoyle",450,15);
cout << monster2.getHealth() << endl;
monster.attack(monster2);
cout << monster2.getHealth() << endl;
}
monster.h
#ifndef MONSTER_H
#define MONSTER_H
#include <iostream>
#include <string>
using namespace std;
class Monster
{
public:
Monster(string name_, int health_, int damage_);
~Monster();
int attack(Monster opponet);
int getHealth();
string name;
int damage;
int health = 0;
int getDamage();
void setHealth(int health_);
void setDamage(int damage_);
void setName(string name);
void doDamageToOpponent(Monster opponent);
string getName();
};
#endif
monster.cpp
#include "monster.h"
Monster::Monster(string name_, int health_, int damage_) {
health = health_;
setDamage(damage_);
setName(name_);
}
Monster::~Monster() { }
int Monster::attack(Monster opponent) {
doDamageToOpponent(opponent);
}
void Monster::doDamageToOpponent(Monster opponent) {
int newHealth = opponent.getHealth() - this->getDamage();
opponent.setHealth(newHealth);
}
int Monster::getHealth() {
return health;
}
int Monster::getDamage() {
return damage;
}
void Monster::setHealth(int health_) {
health = health_;
}
void Monster::setDamage(int damage_) {
this->damage = damage_;
}
void Monster::setName(string name_) {
this->name = name_;
}
string Monster::getName() {
return name;
}
Now my problem is that, when I run this code I expect to have monster2 object to have 400 health left, but it is still 450 :S
What must be done here in order to to so? I noticed that it can be 400 in doDamageToOppoenet but when it leaves that block, then it is still 450. Please help me! Thanks.
You're passing objects by value:
void Monster::doDamageToOpponent(Monster opponent) <- This should be by reference
int Monster::attack(Monster opponent) <- idem
that means: you're creating a new copy of the Monster object you meant to deal damage to in the functions you're calling, and then actually dealing that copy damage but leaving the original old object with the value untouched.
Signatures as follows would work instead:
void Monster::doDamageToOpponent(Monster& opponent)
int Monster::attack(Monster& opponent)
If you want to learn more about this, something to read on: Passing stuff by reference and Passing stuff by value
The reason is that functions attack and doDamageToOpponent are taking copies of arguments, because you pass them by value. What happenes then is you change the copies of passed Monsters inside functions. After functions return, these copies die (as they are local to functions) and nothing happens to original, interested parties.
Try instead pass the argument by reference. Reference works as if it was the original variable. Consider:
int a = 0;
int &refa = a; /* refa acts as real "a", it refers to the same object "a" */
int b = a; /* this is your case */
b = 6; /* b will be changed, but "a" not */
refa = 6; /* a is changed, really "a", refa is just different name for "a" */
Try:
int Monster::attack( Monster &opponent){
doDamageToOpponent( opponent);
}
void Monster::doDamageToOpponent( Monster &opponent){
int newHealth = opponent.getHealth() - this->getDamage();
opponent.setHealth( newHealth);
}
You are passing the opponent by value, i.e., the function:
int Monster::attack(Monster opponent);
will actually receive a copy of the opponent and modify that copy. Every time you have a function that modifies some object you need to pass the object to be modified by reference or pass a pointer to it, e.g.,
int Monster::attack(Monster& opponent);
or
int Monster::attack(Monster* opponent);
I recommend using const T& for input parameters and T* for output parameters, so in this case, the latter form. The reason why I recommend the latter for output parameters is because it makes it more explicit to the caller:
monster.attack(&monster2); // passing a pointer: monster2 will be modified.