繁体   English   中英

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

[英]Re-declaration error when using a prior variable in anonymous instance creation

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

我已经分别在Mac和Linux中分别用4.2和4.7版尝试过。 我也尝试了其他类型而不是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 ++的上下文敏感特性以及编译器如何解释它的情况。

int (i);

被视为“ i”的声明(并且由于在此作用域中已经有一个名为i的变量并且尚未启用-Wno-shadow,因此不允许这样做)。

与以下情况(未编译)形成对比:(请参阅http://ideone.com/QuwnTC

#include <iostream>

class Bark {
public:
    Bark(const char* msg, const char*) {
         std::cout << "Hear ye, hear ye. " << msg << std::endl;
    }
};

void bark(const char* i) {
    Bark (i); // error here.
}

int main(int argc, const char* argv) {
    bark("wtf");
}

它抱怨说,树皮(i)遮盖了“ i”的声明。

但是,以下两个DO都可以编译: http : //ideone.com/dcGMET

void bark(const char* i) {
    Bark (i + 1);
}

或在圆括号内有两个参数:( http://ideone.com/tMzSY9

#include <iostream>

class Bark {
public:
    Bark(const char* msg, const char*) {
         std::cout << "Hear ye, hear ye. " << msg << std::endl;
    }
};

void bark(const char* i) {
    Bark (i, NULL);
}

int main(int argc, const char* argv) {
    bark("wtf");
}

显然,这里对“类型(名称)”的处理是一种特殊情况,您可能想向编译器开发人员提出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM