【发布时间】:2015-01-31 18:15:50
【问题描述】:
我的这段代码可以用 clang 编译(即使是 -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,我的 clang 版本是 3.5.0。 我不明白为什么甚至应该存在阴影问题。就算有,也应该是被clang捡起来的。
【问题讨论】:
-
你能解决阴影问题,让两个编译器都满意吗?还是你说你根本不理解错误信息?
-
这似乎被解释为
PhonebookWriter fname("Mr Foo Bar", "12345"),即作为本地实例的声明。您可以使用临时或命名的工厂函数来解决它,甚至只是在PhonebookWriter(fname)周围加上一对括号。 -
是的,我可以解决这个特定示例中的阴影问题。但是,我不明白为什么首先会出现问题,以及为什么不同的编译器对该代码的响应不同。
-
我一开始就试图避免使用临时变量。添加额外的括号就可以了。谢谢。
-
关于潜在问题的线程:stackoverflow.com/questions/28283215/…