Access Struct Object Variable within Class - C++ - c++

I'll try and explain this the best I can...
Basically, I'm writing this program for a GBA game and I'm trying to change a member variable of a struct instance from within a class. This is the code, omitting unnecessary parts:
player.cpp
#include "player.h" // Line 1
#include "BgLayerSettings.h"
player::player(){
x = 16;
y = 16;
health = 5;
direction = LEFT;
dead = false;
}
player::~player(){
}
// Omitted unrelated code
void player::ScrollScreen(){ // Line 99
if(x>((240/2)-8)){
BACKGROUND_2.h_offset += x-((240/2)-8);
}
}
player.h
#include <stdint.h> // Line 1
#include <stdlib.h>
#include <string.h>
#include "gba.h"
#include "font.h"
#pragma once
class player {
public:
player();
~player();
unsigned int x;
unsigned int y;
void ScrollScreen();
};
BgLayerSettings.cpp
#include "player.h" // Line 1
#include "BgLayerSettings"
BgLayerSettings::BgLayerSettings(){
charblock = 0;
screenblock = BLANK;
v_offset = 0;
h_offset = 0;
}
BgLayerSettings::~BgLayerSettings(){
}
BgLayerSettings.h
#include <stdint.h> // Line 1
#include <stdlib.h>
#include <string.h>
#include "gbs.h"
#include "font.h"
#pragma once
enum BACKGROUND {bg0=0, bg1, bg2, bg3, bg4, bg5, bg6, bg7,
bg8, bg9, bg10, bg11, bg12, bg13, bg14, bg15,
bg16, bg17, bg18, bg19, bg20, bg21, bg22, bg23,
bg24, bg25, bg26, bg27, bg28, DUNGEON_1, DUNGEON_FLOOR, BLANK,
};
struct BgLayerSettings {
public:
BgLayerSettings();
~BgLayerSettings();
unsigned int charblock;
BACKGROUND screenblock;
int v_offset;
int h_offset;
};
main.cpp
#include "player.h" // Line 1
#include "BgLayerSettings.h"
player Player;
BgLayerSettings BACKGROUND_0;
BgLayerSettings BACKGROUND_1;
BgLayerSettings BACKGROUND_2;
BgLayerSettings BACKGROUND_3;
// Omitted unrelated code
Essentially I'm trying to change the variable h_offset of the object BACKGROUND_2 from within the player class.
When I try to compile this, I receive this error:
player.cpp: In member function 'void player::ScrollScreen()':
player.cpp:101:3: error: 'BACKGROUND_2' was not declared in this scope
make: *** [player.o] Error 1
No matter what I try, I cannot get past this error. Anyone able to shed some light on this for me?
Thanks in advance.

It doesn't look like Player.cpp, specifically this line...
BACKGROUND_2.h_offset += x-((240/2)-8);
can see the instance of BACKGROUND_2. If you are instantiating it in main.cpp then there'd be no way for Player.cpp to see that during the build. You should pass whatever background you want to change into the function as a reference and change it from the main.cpp. Something like this instead...
void player::ScrollScreen( BgLayerSettings &bg ){ // Line 99
if(x>((240/2)-8)){
bg.h_offset += x-((240/2)-8);
}
}
Your main.cpp would be something like this...
player1.ScrollScreen( BACKGROUND_2 );

Related

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);

extern vector created in constructor

I have a class Team and a class Ball and I create a vector in constructor of Team that is filled with objects of another class called Player. So I want to use this vector in the class Ball but even though I define it as extern (public) compiler keeps telling me that I have undefined reference to team that is my vector. Here follows the code of Team.cpp and Ball.cpp
Team.h
#define TEAM_H
#include <iostream>
#include <vector>
#include "Player.h"
using namespace std;
extern vector<Player> team;
class Team {
public:
Team();
void fillTeamVector(vector<Player>&);
private:
string teamName;
int faults;
int passes;
int goals;
};
#endif // TEAM_H
Team.cpp
#include "Team.h"
#include <vector>
#include <iostream>
#include "Player.h"
#include "Attacker.h"
#include "Defender.h"
#include "Ball.h"
Team::Team()
{
extern vector<Player> team;
fillTeamVector(team);
}
void Team::fillTeamVector(vector<Player>& team){
// do stuff and store them on vector team
}
And here follows the code for Ball.h note that I commented all the methods that don't affect the problem.
#ifndef BALL_H
#define BALL_H
#include "Player.h"
class Ball
{
public:
Ball();
Player* current;
Player* previous;
/*void setX_ball(int);
int getX_ball() const;
void setY_ball(int);
int getY_ball() const;*/
void assign();
//void changeCurrentToPrevious();
//void changeNextToCurrent(Player*);
private:
int X_ball;
int Y_ball;
};
#endif // BALL_H
Here is the code for Ball.cpp note that in method assign if I create a new (and obviously different vector of Player named team it will compile correctly)
#include "Ball.h"
#include "Team.h"
#include "Player.h"
extern vector<Player> team;
Ball::Ball()
: X_ball(2),
Y_ball(5)
{
current = NULL;
previous = NULL;
}
void Ball::assign(){
//vector<Player> team;
int x;
int y;
x=(team[0].getX())-X_ball;
y=(team[0].getY())-Y_ball;
int min=x+y;
int k=0;
for (int i=1; i<team.size(); i++){
x=(team[i].getX())-X_ball;
y=(team[i].getY())-Y_ball;
int sum=x+y;
if(sum<min){
k=i;
}
}
current = &team[k];
}
By doing
extern vector<Player> team;
you only declare the variable.
In one source file you must actually define the variable:
vector<Player> team;
Note the lack of extern in the definition.
Also note that this has to be done in the global scope, since you want a global variable. So it has to be defined outside of any functions or classes or namespaces.

C++ Undefined reference to Holder::menus (Struct)

Ok, so I have a struct defined as thus:
#ifndef __STRUCTS_H__
#define __STRUCTS_H__
struct counts {
int views = 0;
int inits = 0;
};
#endif
I have a class that is going to have entirely static methods and variables that are accesable by all classes.
#ifndef __HOLDER_H__
#define __HOLDER_H__
#include "Structs.h"
class Holder
{
public:
static counts menus;
Holder() {
menus = counts();
}
};
#endif
And so I tried to acess this method and the compiler spits out the error "Undefined reference to Holder::menus"
Here is the segment that triggers this (HelloWorldScene.cpp)
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
#include "Holder.h"
#include "Structs.h"
USING_NS_CC;
HelloWorld::HelloWorld(void)
{
//Constructor
Debug::crashLog("**__Menu Deinit__**");
//SUDO Missing stuff
Holder::menus.inits -= 1;
}
Why is it having issues?
in your Holder implementation file you need this:
counts Holder::menus;
if you don't have Holder.cpp file, (and you don't want one) you can put it directly into in HelloWorldScene.cpp.

In member function I get the error " invalid use of undefined type 'struct (name)' - forward declaration of 'struct (name)' "

I have the following files in the same project.
Don't bother reading all the blocks of code if you think it's not necessary,
the error messages appear only in the ship.cpp
main.cpp
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
#include "chart.cpp"
#define N 10
using namespace std;
int main()
{
int i,j, flagi=-3, flagj=-3;
int test, ports_count=0, treas_count=0;
chart ***mapp;
mapp=new chart **[N];
for(i=0;i<N;i++){mapp[i]=new chart *[N];}
/*missing code initilazing chart ***mapp */
return 0;
}
chart.cpp
#include <iostream>
#include "ship.cpp"
using namespace std;
class chart{
bool isPort;
int weather;
int treasure;
ship* shipPtr;
public:
chart(){isPort=false; weather=0; treasure=0; shipPtr=NULL;}
bool getPort(){return isPort;}
int getWeather(){return weather;}
int getTreasure(){return treasure;}
ship* getShip(){return shipPtr;}
void setPort(bool port){isPort=port;}
void setWeather(int weath){weather=weath;}
void setTreasure(int treas){treasure=treas;}
void setShip(ship* shp){shipPtr=shp;}
};
and
ship.cpp
#include <iostream>
#define N 10
using namespace std;
class ship{
protected:
string name;
int maxhp, curhp, speed, curtreas, x_pos, y_pos;
public:
friend class chart;
//the line above gives error message " forward declaration of 'struct chart' "
static int shipcount;
ship(){shipcount++;}
string getName(){return name;}
int getMaxhp(){return maxhp;}
int getCurhp(){return curhp;}
int getSpeed(){return speed;}
int getCurtreas(){return curtreas;}
int getX_pos(){return x_pos;}
int getY_pos(){return y_pos;}
bool Move(chart ***mapp){
int x, y, blocked=0;
for(x=x_pos-1;x<=x_pos+1;x++){
if((x>-1) && (x<N)){
for(y=y_pos-1;y<=y_pos+1;y++){
if((y>-1) && (y<N)){
/* the line below gives error message "invalid use of undefined type 'struct chart'"*/
if((!mapp[x][y]->getPort) && (mapp[x][y]->getShip==NULL)){
blocked++;
}
}
}
}
}
if(blocked<2){
return false;
}
/* missing the rest of the body of bool Move cause it is too big */
}
}
The compiler gives the following error messages:
"invalid use of undefined type 'struct chart' " in ship.cpp -> line 39
"forward declaration of 'struct chart' " in ship.cpp -> line 12
Why are these errors showing up?
I know the code is probably complex but any help would be appreciated.
Thank you for your time.
The reason this code does not compile is that your ship.cpp file needs a definition of chart class in order to use its members. You fail to provide this definition, prompting the compiler to complain.
Since all of the members of class chart are defined in the class declaration, you can rename chart.cpp to chart.h, and add an #include for it in your ship.cpp file:
#include <iostream>
#include "chart.h"
#define N 10
... // The rest of ship.cpp code
Also replace the name chart.cpp in your main with chart.h.

undeclared identifier when function is in cpp file

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;
// ^^^^^