I've programmed a lot with C but just started a new job using C++. If you could point me in the right direction, I would appreciate it.
I made a bare-bones example that shows my problem. Here's what I'm trying to do in words:
I have a class called 'Top' that instantiates two objects called 'a' and 'b'. I want to override the << operator for 'b'. The problem is, there is some data in 'a' that 'b' needs to know to properly stream 'b'.
My strategy is to use the 'Top' constructor to place a pointer to 'a' inside 'b'. Then when 'b' needs data from 'a', it can do: Aptr->aData or Aptr->getaData.
PROBLEMS:
1. Line 27. The compiler says this needs to be 'static'. I thought 'static' just made the var the same for all instances of the object instead of making a separate var for each instance. Why is it insisting on 'static'?
2. When I use 'static', the program compiles but doesn't link. Why not?
3. I need line 42 to work.
4. Am I using the right approach or am I making this too hard? Other suggestions?
Thanks!
#include <iostream>
#include <vector>
using namespace std;
class Top;
class A
{
public:
A(): aData(123) {}
int aData;
};
class B
{
public:
void setAptr(A* val){Aptr = val;}
int getAData(void){return Aptr->aData;}
friend ostream& operator<<(ostream& os, B b)
{
os << Aptr->aData; // THIS IS KEY. I WANT TO ACCESS
// PROPERTY OF SIBLING OBJECT.
return os;
}
A* Aptr; // Filled in with Top constructor
// static A* Aptr; // Compiles with 'static' but won't run
};
class Top
{
public:
A a;
B b;
Top() {b.setAptr(&a);} // Give obj 'b' a pointer to obj 'a'
};
int main() {
Top t;
cout << t.b.getAData(); // This works
// cout << t.b; // I want this to work
return 0;
}