gpt4 book ai didi

C++ - 我可以同时对多个文件使用 extern 和 const 吗?

转载 作者:行者123 更新时间:2023-11-28 01:30:37 26 4
gpt4 key购买 nike

问题是我试图为所有 .h.cpp 文件设置一个全局常量变量,但是当我这样做时出现错误:

array bound is not an integer constant before ‘]’ token

我不明白这一点,因为 Z 是一个常量。当我只用一个文件执行此操作时,它就可以工作。我究竟做错了什么?


数字.h

#include <iostream>

extern const int Z;

a.cpp

#include <iostream>
#include "b.h"
#include "c.h"
#include "Number.h"
using namespace std;


int main() {
const int Z = 5;
b Objeto1;
c Objeto2;
double H[Z][Z];
Objeto1.Algo(H);
Objeto2.Imprimir(H);
return 0;
}

b.h

#include <iostream>
#include "Number.h"

class b {
public:
void Algo(double[Z][Z]);
};

b.cpp

#include <iostream>
#include "b.h"
#include "Number.h"
using namespace std;

void b::Algo(double H[Z][Z]) {
for(int a = 0; a < Z; a++) {
for(int b = 0; b < Z; b++) {
H[a][b] = Z;
cout << H[a][b] << endl;
}
}
}

c.h

#include <iostream>
#include "Number.h"

class c {
public:
void Imprimir(double H[Z][Z]);
};

c.cpp

#include <iostream>
#include "c.h"
#include "Number.h"

using namespace std;
void c::Imprimir(double V[Z][Z]) {
cout << "dfs" << endl;
}

我知道代码没有任何意义,但我只是想了解如何为所有文件设置一个常量。非常感谢您的帮助。

最佳答案

使用

extern const int Z;

完全没问题。但是,您不能使用 Z 来定义数组。因此,在下一行和类似的其他行中使用 Z 是不正确的。

class b{
public:
void Algo(double[Z][Z]);

};

数组的大小必须在编译时已知。对于您提供的 extern 声明,这是不正确的。

extern const 的使用仅在您希望在运行时定义值并期望该值在程序结束之前不会更改时才是合理的。

如果您只是想将它用作定义数组的标记,请删除 extern 并同时设置它的值。使用:

const int Z = 5;

关于C++ - 我可以同时对多个文件使用 extern 和 const 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51689618/

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