gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:42:18 27 4
gpt4 key购买 nike

树中的每个类都依赖于与其他类的关系,用于监视电压和电流传感器(通常命名为 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com