2010-06-26 60 views
1

我的问题可能不会太正确的......我的意思是:如何将类元素中的变量传递给类元素? (C++)

class MyClass 
{ 
public: 
    MyClass() 
    { 
    } 

    virtual void Event() 
    { 
    } 
}; 

class FirstClass : public MyClass 
{ 
    string a; // I'm not even sure where to declare this... 

public: 
    FirstClass() 
    { 
    } 

    virtual void Event() 
    { 
     a = "Hello"; // This is the variable that I wish to pass to the other class. 
    } 
}; 

class SecondClass : public MyClass 
{ 
public: 
    SecondClass() 
    { 
    } 

    virtual void Event() 
    { 
     if (a == "Hello") 
      cout << "This is what I wanted."; 
    } 
}; 

我希望,这使得至少有一点点感觉...

编辑:_This改为a

+1

这绝对不清楚;你想在不同的类的不同实例之间用一个共同的父类传递数据,但是在父类中没有数据交换域?它有什么意义?你想达到什么目的? – 2010-06-26 13:56:05

+0

我想_这是相同的_This在其他孩子类。事情是,我不知道缺少什么。数据交换领域应该是什么样子? – Neffs 2010-06-26 14:02:19

+1

顺便说一下,'_This'是一个保留名称,因为它以'_'和一个大写字母开头;你应该改变它别的东西。 – 2010-06-26 21:35:17

回答

4

你需要做的是使SecondClass继承自FirstClass并声明_This为protected。

class FirstClass : public MyClass 
{ 
protected: 
    string _This; 

public: 

class SecondClass : public FirstClass 

你有没有意义,因为类只能看到成员和职能,从他们的父母(在你的情况MyClass的)什么。仅仅因为两个类从同一父类继承并不意味着他们彼此之间有任何关系或知道任何关系。

此外,protected意味着从此类继承的所有类将能够看到其成员,但没有其他人。

+0

感谢您的帮助! – Neffs 2010-06-26 14:12:16

1

我想,你需要像这样(为简单的缘故,我省略所有不必要的代码):

class Base{ 
public: 
    ~Base(){} 
protected: 
    static int m_shared; 
}; 

int Base::m_shared = -1; 

class A : public Base{ 
public: 

    void Event(){ 
     m_shared = 0; 
    } 

}; 

class B : public Base{ 
public: 

    void Event(){ 
     if (m_shared == 0) { 
      m_shared = 1; 
     } 
    } 
}; 


int _tmain(int argc, _TCHAR* argv[]) 
{ 
    A a; 
    B b; 

    a.Event(); 
    b.Event(); 
    return 0; 
} 

为了解释上述,我将解释静态数据成员:

非静态成员对于每个类实例是唯一的,并且不能在类实例之间共享它们。另一方面,静态成员由类的所有实例共享。

p.s.我建议你阅读this书(特别是Observer模式)。还要注意上面的代码不是线程安全的。

+0

谢谢! – Neffs 2010-06-26 14:36:35