在匿名实例创建中使用先前声明的变量时,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/