【问题标题】:Accessing one class member in another class [closed]访问另一个班级中的一个班级成员[关闭]
【发布时间】:2020-09-14 08:05:59
【问题描述】:
class A
{
 public:
    int m_count;
    int m_values[300];
    void Method1();
}
class B
{
    void Method2();
}

void A::Method1()
{
    for(int i=0; i<m_count; i++)
    {
        creates instances of class B
    }
}

B::Method2() 对于 B 类的每个实例都需要 A 类的 m_values 数组。这里 m_values 由 A 类中的另一个函数每分钟更新一次。 是否可以在 B 类的所有实例中访问 A 类的 m_values?

【问题讨论】:

  • m_values A 的哪个类实例?
  • A 类只有一个实例
  • 请填写m_countm_values的类型。
  • 并添加私有/公共限定符。
  • 请发布真实代码/minimal reproducible example 和编译器错误。在此处发布的内容中引入其他错误只会使问题更难理解。

标签: c++ c++11 c++14


【解决方案1】:
class A {
private:
    Type m_values[300];
public:
    Type getValue(int index) { return m_values[index]; }
};

class B {
private:
    A &a;
public:
    void Method2() { /* can call a.getValue(<number>); */ }
    B b(A &a) : a(a) {}
};

void A::Method1()
{
    for(int i=0; i<m_count; i++) {
        creates instances of class B
        B b(*this);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 2017-06-20
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    相关资源
    最近更新 更多