sách gpt4 ai đã đi

c++ - 覆盖静态成员和 "static static arrays"

In lại 作者:行者123 更新时间:2023-11-28 03:54:29 32 4
mua khóa gpt4 Nike

“覆盖”静态数组时我遇到了一个棘手的问题。我有静态数组(为简单起见),它们在不同的派生类中具有固定长度,但在编译时仍然知道所有大小。我在基类中也有一个虚函数,但我不知道如何解决在派生类中覆盖这些数组和数组大小的问题,以便这个虚函数正常工作,即给出大小和数组派生类的内容。示例:

class B {
riêng tư:
// these two are not really meaningful in this class (ABC)
static const int n = 1;
static double da[n];
công cộng:

virtual void f()
{
for(int i = 0; i < n; ++i)
{
// do something with n and da
std::cout << n << std::endl;
}
}
};

class D1 : public B {
riêng tư:
// these are subclass-specific (i.e. n might also change)
static const int n = 4;
static double da[n];
};

class D2 : public B {
riêng tư:
// these are subclass-specific (i.e. n might also change)
static const int n = 6;
static double da[n];
};


double D1::da[] = {1., 2., 3., 4.};
// ...

int chính()
{
B *p = new D;
p->f(); // I'd like to see 4 instead of 1
}

您能否建议一个修复或正确执行此操作的不同方法?我认为 std::vector 会这样做(?),但需要做很多工作才能适应我现有的代码。非常感谢,彼得

1 Câu trả lời

由于 f 仅在 Base 类中定义,它将使用该类的 n 变量。

也许移动:

for(int i = 0; i < n; ++i) 
{
// do something with n and da
std::cout << n << std::endl;
}

到一个单独的函数,而是拥有它,这样你就可以传入“n”是什么。喜欢

void doStuff(int num) {
for(int i = 0; i < num; ++i)
{
// do something with n and da
std::cout << num << std::endl;
}
}

让每个子类实现 f() 来调用 doStuff(n),其中 n 将是每个类自己的 n 变量。

关于c++ - 覆盖静态成员和 "static static arrays",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4155809/

32 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com