Accessing initialized variable on different class C++
I'm having some difficulties with this problem.
The main idea is, I initialized a variable of class type B in class A, class A.h has the variable Z declared as public, like B *Z;
In class A.cpp, I initialized it as Z = new B();
Now, I want to access that variable from class C and I'm unable to do so. C.h includes A.h and B.h
Here goes a bit of code:
Car.h
#include "Model.h"
class Car {
public:
static Model *Z;
}
Car.cpp
#include "Car.h"
void Ca开发者_运维知识库r::init() {
Z = new Model();
}
Model.h
Class Model {}
Camera.h
#include "Model.h"
#include "Car.h"
class Camera {}
Camera.cpp
Camera::init() {
Car::Z->getPos();
}
I initialized a variable of class type B in class A
#pragma once
#include "B.h"
class A
{
public:
B* Z;
A()
{
Z = new B();
}
}
B.h
#pragma once
class B
{
}
C.h
#pragma once
#include "A.h"
class C
{
A a; //here you construct A
C()
{
a.Z = new B(); //you can read/write Z
}
}
This should work! Be careful to include the #pragma once
or a header guard/include guard (http://en.wikipedia.org/wiki/Header_file) so the headers won't be included twice (if should have done it).
There are 3 classes, car, model and camera. in car I declare a new model Z and I want the camera to follow that model so I'll have to access the model positions in camera class
- A = Car
- B = Model
- C = Camera
Are you doing something like this?
class A{
public:
A() : m_B( new B() );
B* getB() const { return m_B;}
private:
B *m_B;
};
class C{
public:
B* getB() const { return m_A.getB(); }
private:
A m_A;
};
So you have
class A {
public:
B* Z;
};
class B {
public:
// Empty
};
class C {
public:
// Empty
};
So to say...there is no reason why you SHOULD be able to access Z. Your question ist not percice enough to say...but you should do
class C {
public:
A* z_access;
};
Now you can use "a" Z in class C by using class A. But we need more information to see what is really going on.
Based on the updated question:
Your problem is that you have not actually defined the Car::Z
variable anywhere. You have a declaration for it in the Car
class, but there is no definition anywhere.
What you need is to add, in the car.cpp file, the line:
Model* Car::Z;
Or, optionally, if you want to give Z
an initial value, something like:
Model* Car::Z = NULL;
This is needed in general for static member variables that are anything other than constant integers. You need the declaration in the class { }
block, and then you also need a definition in the corresponding .cpp file, otherwise you will get this error.
Is it a static variable? If not you have to access it from an instance of class A.
From what you wrote, it sounds like it's static though. In that case, in A.h you have to say
static B *Z;
Then in A.cpp, you have to define it:
B *A::Z;
Then in C.cpp, you can access it like
A::Z->whatever();
精彩评论