c++ - 在类定义中使用内置数组,但将大小推迟到派生类会导致隐藏吗?

标签 c++ inheritance composition

树中的每个类都依赖于与其他类的关系,用于监视电压和电流传感器(通常命名为 1、2、3...)。问题在于这些传感器中有多少取决于所模拟的单元类型;这意味着只有派生类会知道这一点。

#include <iostream>
class A {
public: 
     A() {};
     virtual void Display() = 0;
protected:
     int array[]; // size is purposefully left out in base class
};

class B : public A {
public:
     B(int numbers[4]);
     virtual void Display();
protected:
     int array[4]; // 4 sensors are required, number fixed at compile time
}

B::B(int numbers[4]) {
     for(int i=0; i<4; i++)
          array[i] = numbers[i];
}

void B::Display() {
     cout << " B numbers are: ";
     for(int i = 0; i < 4; i++)
          cout << array[i] << " ";
     cout << endl;
}

class C : public A {
public: 
     C(int numbers[8]);
     virtual void Display();
protected:
     int array[8]; // 8 sensors needed, number fixed at compile time
};

C::C(int numbers[8]) {
     for(int i=0; i<8; i++)
          array[i] = numbers[i];
}

void C::Display() {
     cout << " C numbers are: ";
     for(int i = 0; i < 8; i++)
          cout << array[i] << " ";
     cout << endl;
}

此驱动程序表明这在使用 g++ 编译器时在技术上是可行的,但我担心我可能会通过在 B 和 C 类中重新声明数组来隐藏数据。

main() {
    int B_numbers[] = {1,2,,3,4};
    int C_numbers[] = {5,6,7,8,9,10,11,12};
    B b(B_numbers[]);
    C c(C_numbers[]);
    b.Display();
    c.Display();
}

感谢您提供的任何建议。

最佳答案

您显示的任何代码中都没有使用 A::array,因此您可以将其删除为不必要的。 BC 有他们自己的个人数组,他们各自对 Display() 的覆盖知道如何处理 - A这里不需要涉及。只需:

struct A {
    virtual void Display() = 0;
};

请注意,就构造函数而言,B(int numbers[4]); 实际上与 B(int *numbers) 没有任何区别,那里的数字只是给人一种安全的错觉——我可以很容易地将错误大小的数组传递到那里。出于这个原因,更喜欢使用 std::array - 它具有可复制构造的额外好处:

class B : public A {
public:
     B (std::array<int, 4> const& arr)
     : array(arr)
     { }

     virtual void Display();
protected:
     std::array<int, 4> array;
}

关于c++ - 在类定义中使用内置数组,但将大小推迟到派生类会导致隐藏吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36898399/

相关文章:

java - java中什么时候运行非静态 block ?

inheritance - 在需要将行为添加到List <>的情况下,使用组合而不是继承有什么优势?

c++ - 使用按位运算符和 bool 逻辑的绝对值 abs(x)

c++ - If 语句错误地识别括号中的空格

c# - 内部抽象方法。为什么会有人拥有它们?

c++ - C++派生类中的反射工厂无法访问 protected 方法?

function - "chain"将加法运算符转换为接受 3 个参数的函数?

javascript - 如何将实例变量从 React 组件传递给它的 HOC?

c++ - 将文件读入 std::string 的最有效方法是什么?

c++ - C++11 中的用户定义属性?