2015-01-31 38 views
4

我有這段代碼與鏗鏘編譯(即使使用-Weverything),但爲此gcc發出錯誤。代碼與叮噹編譯,但不與海合會

#include <iostream> 
#include <vector> 
#include <fstream> 

using namespace std; 

class PhonebookWriter 
{ 
public: 

    PhonebookWriter(const string& fname): 
    fname_(fname), names_(), numbers_() {} 

    PhonebookWriter& operator()(const string& name, 
        const string& number) 
    { 
    names_.push_back(name); 
    numbers_.push_back(number); 
    return *this; 
    } 

    ~PhonebookWriter(void) 
    { 
    ofstream f(fname_.c_str()); 
    for(size_t i=0;i<names_.size();++i) 
     f << names_[i] << " " << numbers_[i] << "\n"; 
    f.close(); 
    } 

private: 
    const string fname_; 
    vector<string> names_; 
    vector<string> numbers_; 
}; 

namespace { 
    void write_guests_data(const string& fname) 
    { 
    PhonebookWriter(fname)("Mr Foo Bar","12345")("Mrs Bar Foo","54321"); 
    } 
} 

int main(void) 
{ 
    write_guests_data("phone_book.txt"); 

    return 0; 
} 

和這裏就是我得到的,當我嘗試編譯代碼:

$ g++ ./test.cpp 
./test.cpp: In function ‘void {anonymous}::write_guests_data(const string&)’: 
./test.cpp:39:27: error: declaration of ‘PhonebookWriter fname’ shadows a parameter 
    PhonebookWriter(fname)("Mr Foo Bar","12345")("Mrs Bar Foo","54321"); 
         ^
./test.cpp:39:48: error: no matching function for call to ‘PhonebookWriter::PhonebookWriter(const char [11], const char [6])’ 
    PhonebookWriter(fname)("Mr Foo Bar","12345")("Mrs Bar Foo","54321"); 
               ^
./test.cpp:39:48: note: candidates are: 
./test.cpp:11:3: note: PhonebookWriter::PhonebookWriter(const string&) 
    PhonebookWriter(const string& fname): 
^
./test.cpp:11:3: note: candidate expects 1 argument, 2 provided 
./test.cpp:7:7: note: PhonebookWriter::PhonebookWriter(const PhonebookWriter&) 
class PhonebookWriter 
    ^
./test.cpp:7:7: note: candidate expects 1 argument, 2 provided 
./test.cpp:39:49: error: expected ‘,’ or ‘;’ before ‘(’ token 
    PhonebookWriter(fname)("Mr Foo Bar","12345")("Mrs Bar Foo","54321"); 
               ^

我的gcc版本是4.9.1,和我的鐺的版本是3.5.0。 我不明白爲什麼應該有陰影問題。即使有,它應該已經被叮噹拾起。

+0

你能解決影子問題嗎?這樣兩個編譯器都快樂嗎?還是你說你根本不明白錯誤信息? – 2015-01-31 18:19:18

+1

這被解釋爲'PhonebookWriter fname(「Mr Foo Bar」,「12345」)'看起來,即作爲本地實例的聲明。您可以使用臨時或命名工廠函數,或者甚至只是圍繞'PhonebookWriter(fname)'的一對括號來解決它。 – 2015-01-31 18:25:43

+0

是的,我可以在這個特定的例子中修復陰影問題。但是,我不明白爲什麼首先應該存在問題,以及爲什麼不同的編譯器對該代碼的反應不同。 – user2535797 2015-01-31 18:26:43

回答

8

變化:

PhonebookWriter(fname)("Mr Foo Bar","12345")("Mrs Bar Foo","54321"); 

到:

(PhonebookWriter(fname))("Mr Foo Bar","12345")("Mrs Bar Foo","54321"); 

說明

出於某種原因,GCC消除周圍fname牙套,果然行成:

PhonebookWriter fname ("Mr Foo Bar","12345")("Mrs Bar Foo","54321"); 

現在錯誤是有道理的。