簡體   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