简体   繁体   中英

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

g++ gives a re-declaration error when using previously declared variable in anonymous instance creation.

I have the following code in my "weird.cpp" source file:

#include <iostream>

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

The error i am getting is,

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

I have tried this in mac and linux with versions 4.2 and 4.7 respectively. I have also tried with other types instead of int. The result is the same error. Can anyone help me understand this problem? Thanks.

First of all, the parentheses you're using here don't do anything.

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.

What you are saying about an object accepting an int in it's constructor doesn't make sense.

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

I don't really understand what you're trying to achieve here, perhaps this?

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

You could be forgiven for being confused by this, it's a case of C++'s context-sensitive nature and how that is interpreted by the compiler.

int (i);

is being treated as a declaration of "i" (and since you already have a variable called i in this scope and have not enabled -Wno-shadow, it's not allowing this).

Contrast with the following case, which doesn't compile: (see 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");
}

It complains that Bark (i) shadows "i"s declaration.

However, both of the following DO compile: http://ideone.com/dcGMET

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

or having two arguments inside the parenthesis: ( 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");
}

Clearly, the treatment of "type (name)" here is some sort of special case, and you might want to raise this with the compiler developers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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