C++变量重复定义错误:conflicting declaration
C++变量重复定义错误:conflicting declaration
在 C++ 代码中,如果遇到 'conflicting declaration' 错误,通常是因为在同一个作用域内定义了两个或多个名称相同的变量。
例如,以下代码会产生 'conflicting declaration' 错误:
std::cout << '--- int64_t type ---' << std::endl;
int64_t free_int = static_cast<int64_t>(free_byte);
int64_t total_int = static_cast<int64_t>(total_byte);
int64_t free_int_g = free_int / 1024 / 1024 / 1024;
int64_t total_int_g = total_int / 1024 / 1024 / 1024;
std::cout << 'Total global memory: ' << total_int_g << 'G' << std::endl;
std::cout << 'Total available memory: ' << free_int_g << 'G' << std::endl;
// ...
int free_int = (int)free_byte; // 错误:与之前的 int64_t free_int 冲突
错误分析:
上述代码报错的原因是在代码中定义了两个相同名称的变量 free_int,一个是 int64_t 类型的,另一个是 int 类型的。在 C++ 中,不允许在同一个作用域中定义相同名称的变量。
解决方法:
要解决这个错误,可以采取以下两种方法之一:
- 修改变量名称: 将其中一个变量的名称修改为不同的名称,例如将
int free_int修改为int free_int32。 - 删除重复定义: 如果不再需要其中一个变量,可以直接删除其定义,例如只保留
int64_t free_int的定义。
通过以上方法,就可以解决 'conflicting declaration' 错误,并确保代码中每个变量都有唯一的名称。
原文地址: https://www.cveoy.top/t/topic/fzWK 著作权归作者所有。请勿转载和采集!