- Joined
- Apr 14, 2012
- Messages
- 2,585
- Reaction score
- 0
- Points
- 36
Hello everyone,
So Ive been teaching myself C++ lately. One of the things that I keep thinking would be really nice would be if I could call a given function in a class in all objects of that class type. The obvious advantage of this would be that I could take a vessel class and call its key functions (position, forces, rotation updates per frame) for any number of vessels in a simulation, including ones that get defined in sim via dynamic memory.
After a little bit of experimentation it dawned on me that I could do this with static member functions, so I added it to my little program that Im using to test various ways of working with classes. In the class of type B, I wrote it something like this:
I then proceeded to add this to int main()
And started to compile!!!
...at which point the compiler cuffed me on the back of the head & reminded me not to work with non-static members in static functions. :facepalm:
Any suggestions?
So Ive been teaching myself C++ lately. One of the things that I keep thinking would be really nice would be if I could call a given function in a class in all objects of that class type. The obvious advantage of this would be that I could take a vessel class and call its key functions (position, forces, rotation updates per frame) for any number of vessels in a simulation, including ones that get defined in sim via dynamic memory.
After a little bit of experimentation it dawned on me that I could do this with static member functions, so I added it to my little program that Im using to test various ways of working with classes. In the class of type B, I wrote it something like this:
Code:
#pragma once
#include "B.h"
#include "b.h"
class B
{ public:
B(int i);
B(void);
int targetvalue;
~B(void);
static void PlusPlus(); };
Code:
#include "B.h"
#include "b.h"
B::B(int i)
{ targetvalue = i; }
B::B(void)
{ targetvalue = 0; }
void B::PlusPlus()
{ targetvalue++; }
B::~B(void)
{ }
I then proceeded to add this to int main()
Code:
B B_one(2);
B B_two(4);
B.PlusPlus();
And started to compile!!!
...at which point the compiler cuffed me on the back of the head & reminded me not to work with non-static members in static functions. :facepalm:
Any suggestions?