-3

i have a variable map dataa ehich is used in three different class.i can define this variable globally and put all classes defination in one cpp file but i want to make different files for three different class and thus cant define it globally.

now i want to define this variable in one class say A and then want to use this dataa in the rest two class say B and C.

how can i do this.thanks for anyhelp in advance

4

3 回答 3

0

您可以使用公共 get 和 set 方法来访问 A 类中的变量。或者只是在 A 类中创建一个公共变量。

于 2012-07-09T14:12:02.960 回答
0

或者,您可以尝试将此变量映射数据作为新单例类的一部分。其余 3 个不同的类可以使用 get 方法访问这个单例类

文件:singleton.h

#include <iostream>
using namespace std;

class singletonClass
{
  public:
      singletonClass(){};
      ~singletonClass(){};

  //prevent copying and assignment
  singletonClass(singletonClass const &);
  void operator=(singletonClass const &);

  //use this to get instance of this class
  static singletonClass* getInstance()
  {
     if (NULL == m_Singleton)  //if this is the first time, new it!
        m_Singleton = new singletonClass;

     return m_Singleton;
  }

  int getData()
  {
     return data;
  }

  void setData(int input)
  {
      data = input;
  }
  private:
    static singletonClass* m_Singleton;  //ensure a single copy of this pointer
    int data;
 };
 //declare static variable as NULL
singletonClass* singletonClass::m_Singleton = NULL;

文件:ClassA.h

class ClassA
{
  public:
      ClassA(){};
      ~ClassA(){};

     int getVarFromSingleton()
     {
          m_Singleton = singletonClass::getInstance();  //get a pointer to the singletonClass
          return data = m_Singleton->getData();  //get data from singleton class and return this value
     }
  private:
     singletonClass* m_Singleton;  //declare a pointer to singletonClass
     int data;
 };

文件:main.cpp

int main()
{
singletonClass* DataInstance;
ClassA a;
int data;

DataInstance = singletonClass::getInstance();

DataInstance->setData(5);

data = a.getVarFromSingleton();

cout << "shared data: " << data << endl;

return 0;

}

于 2012-07-09T14:13:37.217 回答
0

你可以用朋友

class A
{
friend class B;
friend class C;
private:
int m_privateMember;
};

class B {
};

class C {
};

现在,B 和 C 可以访问 A 的私有成员。

但这不是最好的方法。尽量避免它。

于 2012-07-09T14:55:44.103 回答