c++ - 在匿名实例创建中使用先前变量时重新声明错误

标签 c++ g++

在匿名实例创建中使用先前声明的变量时,g++ 会给出重新声明错误。

我的“weird.cpp”源文件中有以下代码:

#include <iostream>

int main()
{
  int i = 0;
  int j = int ( i );
  int ( i );
}

我得到的错误是,

weird.cpp: In function ‘int main()’:
weird.cpp:7: error: redeclaration of ‘int i’
weird.cpp:5: error: ‘int i’ previously declared here

我已分别在 4.2 和 4.7 版本的 mac 和 linux 上尝试过此操作。我也尝试过使用其他类型而不是 int 。结果是同样的错误。谁能帮我理解这个问题?谢谢。

最佳答案

首先,您在这里使用的括号没有任何作用。

int i = 0;
int j = int(i); // This is casting i to an int. It's already an int.
int j = i; // This does the same as the last line.
int (i); // This is redeclaring an int named i, which had already been done.
int i; // This is the same as the last line.

您所说的关于在其构造函数中接受 int 的对象没有意义。

struct A { A(int) {} };
int i;
A obj(i); // A instance named obj which takes integer i as constructor argument.

我不太明白你想在这里实现什么,也许是这个?

int i = 0;
int j = i;
{
    int i; // In another scope, shadowing the first i for scope duration.
}

关于c++ - 在匿名实例创建中使用先前变量时重新声明错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19019298/

相关文章:

c++ - 这是一种可接受的资源管理方式吗?

c++ - 如何将 const char* 转换为字符串,然后再转换回 char*?

c++ - 使用 Boost::Asio 通过 TCP 读取二进制数据

c++ - 全局对象中的 "term does not evaluate to a function taking ..."

c++ - 使用 -mpopcnt 编译会导致 Illegal instruction 错误

c++ - 何时以及如何在 C++ 中初始化静态数据?

c++ - wfstream 不写

c++ - g++ 编译单独预处理的文件会根据体系结构给出错误

c++ - 一个定义规则 - 编译

c++ - "to_string"是 't a member of "标准”?