undeclared identifier when function is in cpp file - c++

I'm working on Space Invaders and in my Player Class I'm using a vector of a struct called point to store the coordinates of rockets. For some reason i'm getting "rocketVector : undeclared identifier" when I try to use it in the .cpp file.
Does anyone know why?
I'm still pretty new to C++ and I haven't been able to find a solution on google. it's starting to do my head in now :)
Thanks for any help!
#include <windows.h>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <iostream>
#include <stdio.h>
#include <MMSystem.h>
using namespace std;
class Player
{
public:
Player(void);
~Player(void);
void drawRockets(ISprite *r);
vector<point> rocketVector;
};
Player.cpp
void drawRockets(ISprite *r) {
// Draw appropriate number of rockets
for(int i = 0; i < rocketVector.size(); i++){
if( rocketVector[i].y < 0.0 ){
// Remove rockets off screen
rocketVector.erase(rocketVector.begin() + i);
}
else{
rocketVector[i].y -= 20;
r->draw(int(rocketVector[i].x), int(rocketVector[i].y));
}
}
}

You defined drawRockets as a global function instead of a member function of the Player class.

You need to specify that drawRockets method is a member of the Player class:
void Player::drawRockets(ISprite *r) {
// Draw appropriate number of rockets
for(int i = 0; i < rocketVector.size(); i++){
if( rocketVector[i].y < 0.0 ){
// Remove rockets off screen
rocketVector.erase(rocketVector.begin() + i);
}
else{
rocketVector[i].y -= 20;
r->draw(int(rocketVector[i].x), int(rocketVector[i].y));
}
}
}

You have some errors in your code :
First, when you define a method outside its class, you have to specify it is in a class-scope during the declaration like :
void Player::drawRockets( ISprite *r ) { ... };
// ^^^^^^^^
this will solve your "rocketVector : undeclared identifier" error.
Here the operator of scope (::, two colons) is used to define a member of a class from outside the class definition itself.
Also, it is a very bad practice to to using namespace ... in a header file, you should avoid that.
If you remove the using namespace ... don't forget to transform :
vector<point> rocketVector;
in
std::vector<point> rocketVector;
// ^^^^^

Related

How to declare a <vector> object and use push_back inside a class?

I'm trying to build a class named "Tombola" which should contain as private variable an empty vector. This should be filled at runtime through the class member Tombola.estrai(), which generates a random number and insert it inside the vector named "order" by the method order.push_back(number). This is the class definition in the tombola.h header:
#ifndef TOMBOLA_H
#define TOMBOLA_H
#include <cstdlib>
#include <vector>
using namespace std;
class Tombola {
private:
bool on_off[90];
int tabellone[9][10];
int x_max = 9;
int y_max = 10;
vector<int> order;
public:
Tombola();
~Tombola();
void nuovo();
int estrai();
bool completato();
void stampa();
void stampa_tab();
};
#endif
And this is the implementation of constructor/destructor and Tombola::estrai() inside tombola.cc:
#include "tombola.h"
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <vector>
#include <iostream>
using namespace std;
Tombola::Tombola () {
vector<int> ord;
order = ord;
int z=1;
for(int i=0;i<90;i++) {
on_off[i] = false;
}
for(int j=0;j<=x_max;j++) {
for (int k=0;k<=y_max;k++) {
tabellone[j][k] = z;
z++;
}
}
}
Tombola::~Tombola() {
cout << "Tombola is destroyed" << endl;
}
int Tombola::estrai() {
srand(time(NULL));
int estrazione = int(ceil(rand()/double(RAND_MAX)*90));
on_off[estrazione]==true;
order.push_back(estrazione);
return order.back();
}
and this is the call to the method in the main.cpp file:
#include "tombola.h"
#include <cstdlib>
#include <iostream>
#include <vector>
#include <ctime>
using namespace std;
int main () {
Tombola natale;
cout << natale.estrai();
}
When I compile the program everything goes fine, but when I execute the main I get a segmentation fault error which seems to be due to some sort of allocation error when trying to store the item inside the order vector, as reported by the debugger. Could someone explain to me how to solve the error and why the error occours? Thank you.
The reason of segmentation fault is in the constructor. You have to change for(int j=0;j<=x_max;j++) to for(int j=0;j<x_max;j++) in order not to cross the bounds of the array.
for(int j=0;j<x_max;j++) {
for (int k=0;k<y_max;k++) {
tabellone[j][k] = z;
z++;
}
}
However, there are also some minor issues in the code that are worth being mentioned
declaring default-initialized ord vector and assigning it to order is pointless because order is already default-initialized.(See member initializer list for more information).
using namespace std; in a header file is a terrible idea, because if you had a large codebase, and had multiple source files where you want to include that header, everywhere the using statement will be applied, which probably is not desired.

LNK2005 Already Defined error when linking my library [duplicate]

This question already has answers here:
error LNK2005, already defined?
(8 answers)
Closed 3 years ago.
I've made a library when i try and use it in another project i get a LNK2005 error.
Structs.h
#pragma once
#ifndef STRUCTS_H
#define STRUCTS_H
#include <vector>
#include <string>
namespace Structs
{
struct GameObject
{
std::string name;
struct PosPoints
{
double px;
double py;
};
std::vector<PosPoints> Points;
double centroid[2];
bool active;
bool init;
};
std::vector<GameObject> objects;
}
#endif
Structs.cpp
#include "stdafx.h"
#include "Structs.h"
struct Structs::GameObject gameObject;
std::vector<Structs::GameObject> objects;
CoreFuncs.cpp
#include "stdafx.h"
#include "CoreFuncs.h"
#include "Structs.h"
#include <GLFW/glfw3.h>
//render
extern struct Structs::GameObject gameObject;
void RenderShapes()
{
for (int i = 0; i < Structs::objects.size(); i++)
{
for (int j = 0; j < Structs::objects[i].Points.size()-1; j++)
{
glBegin(GL_LINES);
glVertex3f(Structs::objects[i].Points[j].px, Structs::objects[i].Points[j].py, 0);
glVertex3f(Structs::objects[i].Points[j + 1].px, Structs::objects[i].Points[j + 1].py, 0);
glVertex3f(0.1, 0.1, 0);
glVertex3f(0.9, 0.9, 0);
glEnd();
}
}
}
The issue stops happening when i comment out the #include "Structs.h" in CoreFuncs.cpp So I assume that inlcude is what is causing the issues. I have looked around and found many sources using extern but i cant seem to get it working here.
Your header file is declaring an actual variable instance named objects. Every translation unit that #includes your header file will get its own copy of that variable. So when you link multiple such units together into a single executable, you will get errors about all of the duplicate variables.
It looks like you want the variable to be instantiated only once in your Structs.cpp file and then shared by your other units. So the variable needs to be declared as extern in your header file. You should also move the extern declaration of the gameObject variable from out of your CoreFuncs.cpp file and place it in your header file, too.
Structs.h
#pragma once
#ifndef STRUCTS_H
#define STRUCTS_H
#include <vector>
#include <string>
namespace Structs
{
struct GameObject
{
std::string name;
struct PosPoints
{
double px;
double py;
};
std::vector<PosPoints> Points;
double centroid[2];
bool active;
bool init;
};
extern std::vector<GameObject> objects;
extern GameObject gameObject;
}
#endif
Structs.cpp
#include "stdafx.h"
#include "Structs.h"
namespace Structs {
std::vector<GameObject> objects;
GameObject gameObject;
}
CoreFuncs.cpp
#include "stdafx.h"
#include "CoreFuncs.h"
#include "Structs.h"
#include <GLFW/glfw3.h>
//render
void RenderShapes()
{
for (size_t i = 0; i < Structs::objects.size(); ++i)
{
Structs::GameObject &go = Structs::objects[i];
for (size_t j = 0; j < go.Points.size()-1; ++j)
{
PosPoints &pt1 = go.Points[j];
PosPoints &pt2 = go.Points[j + 1];
glBegin(GL_LINES);
glVertex3f(pt1.px, pt1.py, 0);
glVertex3f(pt2.px, pt2.py, 0);
glVertex3f(0.1, 0.1, 0);
glVertex3f(0.9, 0.9, 0);
glEnd();
}
}
}

Why is my setter method producing a bad access error

Bad access means that i am trying to access memory that doesn't exists I have tried and tried to allocate memory for this class, but have failed everywhere. I do not know where the error is actual coming from. It only tells me that my setter method is when the program crashes. In the setFName() method is where the error occurs. But in the main method is where it actually occurrs.
nurse.hpp
#ifndef Nurse_hpp
#define Nurse_hpp
#include <stdio.h>
#include <string>
#include <stdlib.h>
using namespace std;
class nurse{
private:
string firstName;
public:
nurse() {
firstName = "jim";
}
string getFName() {return firstName;}
void setFName(string fName) {firstName = fName;} // Thread 1: bad access 0x0
};
#endif /* Nurse_hpp */
here is where the error is actually happening
main.cpp
#include <cstdint> // ::std::uint64_t type
#include <cstddef> // ::std::size_t type
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include "nurseHolder.hpp"
using namespace std;
nurseHolder *l = new nurseHolder();
int main() {
return 0;
}
and finally here is the class that is causing the issue
nurseHolder.hpp
#ifndef Nurses_hpp
#define Nurses_hpp
#include <stdio.h>
#include <vector>
#include <stdlib.h>
#include "Nurse.cpp"
using namespace std;
class nurseHolder{
private:
int nurse_cnt;
int nurse_cap;
vector<nurse> nurse_list;
public:
nurseHolder() {
nurse_cnt = 0;
nurse_cap = 10;
for(int i= 0; i < 11; i++){
nurse_list[i].setFName("na");
}
}
vector<nurse> &getNurseList() { return nurse_list;}
};
#endif /* Nurses_hpp */
I tried to make this compact as possible sorry if its a lot of code.
here is what I changed to make the code work:
nurseHolder() {
nurse_cnt = 0;
nurse_cap = 10;
for(int i= 0; i < 11; i++){
nurse l;
nurse_list.pushback(l);
}
}
Is this a correct way to do this?
Your vector nurse_list has size 0. So you cannot use [] operator to set names.
There are two ways you can correct this:
Set an initial size to the vector and use [] to set names.
Use push_back to add elements to the vector.
First method.
nurse_list.resize(noOfTotalNurses).
nurse_list[i].setFName("name");
Second method.
nurse tNurse; //local nurse object
tNurse.setFName("name");
nurse_list.push_back(tNurse);

C++: Why do these functions use different copies of the vector?

I have the problem of class functions making changes on different copies of a vector rather than the one saved in an instance of the corresponding object.
Description of the Main function:
This is the main function. It first creates an object Menno of class Mats, which is initialized with its constructor and has a private vector of type int named F full of values -1. It then is used to create an object of class Calculator named Calli. The object Menno is saved in a private object variable of type Mats named Matrices in Calli. Finally, Matrices is returned by the getMatrices() function of Calli and printF() is carried out on this object variable, which changes values in F and is supposed to change F for all time.
Problem:
As can be seen after executing the program, the changes made by printF() and setf() do not get saved in the object variable Matrices. This leads me to think that the initialization of F in the constructor works well, but the functions then use other copies of this vector rather than the saved one.
Background:
As a Java Coder, I was advised to use pointers for most cases, but I still can't understand why this code doesn't work as intended. I recently investigated C++ as a programming language, went through thenewbostons video guide and printed out syntax lists but they don't help me here. Any explanation is appreciated!
// main function
#include "Calculator.h"
#include "Mats.h"
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int N = 4;
Mats Menno(N);
Calculator Calli(Menno);
Calli.getMatrices().printF();
Calli.getMatrices().setf(2,1);
Calli.getMatrices().printF();
}
// Calculator header
#ifndef CALCULATOR_H
#define CALCULATOR_H
#include "Mats.h"
#include <vector>
class Calculator
{
public:
Calculator(Mats M);
Mats getMatrices();
protected:
private:
Mats Matrices;
};
#endif // CALCULATOR_H
// Calculator cpp
#include "Calculator.h"
#include "Mats.h"
#include <iostream>
#include <vector>
using namespace std;
Calculator::Calculator(Mats M)
: Matrices(M)
{
}
Mats Calculator::getMatrices(){
return Matrices;
}
// Mats header
#ifndef MATS_H
#define MATS_H
#include "Calculator.h"
#include <vector>
class Mats
{
public:
Mats(int N);
int getf(int i);
void setf(int i, int fh);
std::vector<int> getF();
void printF();
protected:
private:
std::vector<int> F;
};
#endif // MATS_H
// Mats cpp
#include "Calculator.h"
#include "Mats.h"
#include <iostream>
#include <vector>
using namespace std;
Mats::Mats(int N)
{
std::vector<int> Fh;
F = Fh;
F.resize(N);
for (int i = 0;i<N;i++){
F[i] = -1;
}
}
int Mats::getf(int i){
return F[i];
}
void Mats::setf(int i, int fh){
F[i] = fh;
}
std::vector<int> Mats::getF(){
return F;
}
void Mats::printF(){
F[1] = 300;
cout << "F: " << endl;
for (int i = 0; i<F.size(); i++) {
cout << F[i] << " ";
}
cout << endl;
F[1] = 200;
}
Because
Mats getMatrices();
returns a copy of the class member. Change it to return it by reference:
Mats &getMatrices();
Note that returning a class member by reference has certain ramifications that you need to understand. You will find all the details in your favorite C++ book.
What happened here is that your self-described background in Java is getting in the way. C++ classes work fundamentally different than Java's classes. You need to forget everything you know about classes, as you know them in Java, and focus on learning how C++ classes work, from the basics.

Why is my array undefined in main when the class headers are included?

So here is the main where i'm trying to call the array by a pointer:
#include <iostream>
#include "Lottery.h"
#include "Player.h"
#include "LotteryData.h"
using namespace std;
int main()
{
Player player;
Lottery random;
LotteryData data;
player.Input();
random.setRandomNumber();
data.PassInfo(int (&Numbers)[6][6]);
}
Apparently "Numbers" is undefined even though the header is included, here's the header and .cpp files relating to it.
LotteryData.h
#pragma once
#include <iostream>
#include <fstream>
#include "Lottery.h"
#include "Player.h"
using namespace std;
class LotteryData
{
private:
public:
LotteryData();
~LotteryData();
void PassInfo(int (&Numbers)[6][6]);
};
LotteryData.cpp
#include <iostream>
#include <fstream>
#include "LotteryData.h"
using namespace std;
LotteryData::LotteryData()
{
}
LotteryData::~LotteryData()
{
}
void LotteryData::PassInfo(int (&Numbers)[6][6])
{
int* ptr;
FILE *Numfile;
Numfile = fopen("C:/Num.txt", "wb");
ptr = &Numbers[6][6];
for (int i=0; i<36; i++)
{
fwrite(ptr, sizeof(int), 36*36, Numfile);
}
fclose(Numfile);
//ofstream out("Numbers.txt");
}
Everything seems fine, I'm puzzled why the reference in the main says the array is undefined, any ideas?
edit: Apologies, missed some bits
Player.h
#pragma once
#include <iostream>
#include <fstream>
using namespace std;
class Player
{
private:
public:
Player();
~Player();
void Input();
int Numbers[6][6];
};
Player.cpp
#include <iostream>
#include <fstream>
#include "Player.h"
using namespace std;
Player::Player()
{
}
Player::~Player()
{
}
void Player::Input()
{
int num(0);
int duplicate = 0;
int game = 0;
int NumberofGames = 0;
cout<<"How many games do you want to play for this weeks draw?"<<endl;
cin>>NumberofGames;
if (NumberofGames>6)
{
cout<<"Please enter an amount between 1 and 6"<<endl;
cin>>NumberofGames;
}
do
{
for (int i=0;i<6;i++)
{
cout<<"Enter Number "<< (i+1) <<endl;
cin>>num;
if (num > 0 && num <67)
{
Numbers[game][i]= num;
}
else
{
cout <<"Please enter number between 1 and 66"<<endl;
i = i-1;
}
}
game = game + 1;
NumberofGames = NumberofGames - 1;
}
while (NumberofGames=0);
}
void PassInfo(int (&Numbers)[6][6]);
That line does not declare an array - it declares a function. You have no declaration for an array in your class (in fact, you have no data members declared in your class at all).
If you want to declare a member array, you need to modify your class definition:
class LotteryData
{
private:
int Numbers[6][6]; // this declares an array
public:
LotteryData();
~LotteryData();
void PassInfo(int (&arr)[6][6]); // this is still a function declaration
};
Just because you made a function's parameter be named Numbers doesn't magically mean that your program has an array called Numbers declared in it.
So a Player has an array called "Numbers".
Then you would use it like this:
data.PassInfo(player.Numbers);
In your main() function,
data.PassInfo(int (&Numbers)[6][6]);
This is wrong. You should simply pass a reference to 2D array.
int (&Numbers)[6][6];
data.PassInfo(Numbers);