C2372 重新定义;不同类型的间接

问题描述

我正在尝试在我的其他文件之一中定义/声明一个 int 数组变量。

Other_file.h

#pragma once
extern int* Test = new int[2]; // <- Here I declare(at least by my understanding)

Other_file.cpp

#include <iostream>
#include "Other file.h"

int* Test[2]; // <- Line that causes error...

然后是 Main.cpp

#include <iostream>
#include "Other file.h"

int main() {
    std::cout << Test;
    return 0;
}

每次我收到这个错误Error C2372 'Test': redeFinition; different types of indirection | Other File.cpp | line 4 仅供参考,我使用的是 MSVC 2019。

解决方法

extern int* Test = new int[2]; // <- Here I declare(at least by my understanding)

不,这是一个定义。这将是声明:

extern int* Test; // note,no value

同样,这两个声明是不兼容的,这就是错误试图告诉你的。 int*[2]int* 完全不同。

,

本声明

extern int* Test = new int[2];

也是一个带有外部链接的指针的定义,因为该指针已被初始化。

然后在源文件 "Other_file.cpp" 中,您将名称 Test 重新定义为 int * 类型的两个元素的数组。

#include "Other file.h"

int* Test[2]; 

所以编译器会报错。

实际上上面的代码片段等价于

extern int* Test = new int[2];
int* Test[2]; 

如果你想声明一个指针,那么在头 "Other file.h" 中声明它就像

extern int* Test;

然后在源文件中"Other_file.cpp"写入

#include "Other file.h"

int *Test = new int[2];