سؤال

Suppose I have class B which gets a value 'v' in the constructor from another class A. How can I read this value from class C? Class C will be instantiated on demand, but A has created B and passed the 'v' already. 'v' will change in every instantiation. I have tried to make 'v' static in Class B. Would it work? I could not implement it properly.

Class A {
 public:
 int* v;
 B b1;
 A(int* var) : v(var), b1(var) {};
}

How to access the same version of 'v' from a C class? I can define B and C however I like in order to achieve the goal. But I cannot change A for that purpose.

هل كانت مفيدة؟

المحلول 2

You cannot access a 'v' which has never passed to the class. Instead you can make a static copy of it as a member in your class A. It will update every time A is instantiated like this:

Class A {
 public:
   int* v;
   static int* staticv;
   ...// Constructor etc
}

in your .cc code of A:

int* A::staticv;
...
A::staticv=this->v;

now any class can access to this value by:

A::staticv;

نصائح أخرى

You need a (public) static member

class A { //let's stick with your naming convention!
public:
  static int a;
}

A::a = 4;

However allowing people to change A::a means that your program will probably end up relying on a global unencapsulated state... which is usually a sign of a bad design.

If you member was const however you are really relating a constant to your class, which is not so bad.

class A {
public: 
  static const int a = 4;
}

std::cout << "A:a is always " << A::a << std::endl;

EDIT BASED ON UPDATED QUESTION If you require help with building a class I would recommend that you use a factory of some kind. If I understand your requirement you want to be able to inject a value into every class A and class B instance. This value "v" is based on a Class C.

So...

class C {
private:
  // up to you where you implement the getUniqueNumberForNow function
  // (global free function for example)
  static const int v = getUniqueNumberForNow();
public:
  static A createA(){
    return A(v);
  }
  static B createB(){
    return B(v);
  }
}

The getUniqueNumberForNow() function just gets whatever your value should be. It will be then stored in class C and can be used during the creation of A an\or B. Now just make A and B's CTORs private and make C a friend of both and you will have only one way to create an A or B, and it will always use the correct value.

See NeilMonday's link in the comments below for info on friend classes.

Last thing is if you want to have the value change for every instantiation of A you can just do this in the factory:

  static A createA(){
    return A(getUniqueNumberForNow());
  }

However if that is really what you want then just do this:

class A {
public:
  A() : val (getUniqueNumberForNow()), b(B(val)){}
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top