下面代码中出现编译错误的代码行(在注释中)有什么问题?我认为应该使用 const std::string 调用 TestMe 构造函数,然后对其调用operator()。但看起来它正在尝试使用变量 a
构造 TestMe
。
#include <iostream>
namespace
{
class TestMe
{
public:
TestMe() {}
TestMe( const std::string& me ) : me_( me ) {}
bool operator()() const
{
std::cout << "calling operator()" << std::endl;
return true;
}
private:
const std::string me_;
};
}
int main()
{
const std::string a("a");
//
// construct an instance of TestMe and call its operator()
//
TestMe()(); // OK
TestMe( "abc" )(); // OK
TestMe tm( a ); // OK
TestMe( a )(); // compile error: what's wrong with this?
TestMe( { a } )(); // OK
return 0;
}
编译错误:
../src/main.cpp: In function ‘int main()’:
../src/main.cpp:44:14: error: ‘{anonymous}::TestMe a()’ redeclared as different kind of symbol
TestMe( a )(); // compile error
^
../src/main.cpp:35:20: note: previous declaration ‘const string a’
const std::string a("a");
最佳答案
“最令人烦恼的解析”:https://www.fluentcpp.com/2018/01/30/most-vexing-parse/
TestMe( a )()
被视为名为 a
的函数的声明,该函数不带参数并返回 TestMe
对象.
稍微更改您的程序,以便相关行不会与名称 a
冲突:
#include <iostream>
namespace
{
class TestMe
{
public:
TestMe() {}
TestMe( const std::string& me ) : me_( me ) {}
bool operator()() const
{
std::cout << "calling operator()" << std::endl;
return true;
}
private:
const std::string me_;
};
}
int main()
{
const std::string a("a");
//
// construct an instance of TestMe and call its operator()
//
TestMe()(); // OK
TestMe( "abc" )(); // OK
TestMe tm( a ); // OK
std::cout << "before most vexing parse\n";
TestMe( b )(); // compiles, but has no effect
std::cout << "after most vexing parse\n";
TestMe( { a } )(); // OK
return 0;
}
您将看到 TestMe( b )();
行不会产生任何输出,因为它只是一个声明:
calling operator()
calling operator()
before most vexing parse
after most vexing parse
calling operator()
关于C++ 创建临时对象来调用成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67498516/