C++ C++;创建临时对象以调用成员函数
下面代码中有编译错误的代码行(注释中)有什么问题?我认为它应该使用C++ C++;创建临时对象以调用成员函数,c++,c++11,C++,C++11,下面代码中有编译错误的代码行(注释中)有什么问题?我认为它应该使用const std::string调用TestMe构造函数,然后对其调用operator()。但是它看起来像是在试图用变量a构造TestMe #include <iostream> namespace { class TestMe { public: TestMe() {} TestMe( const std::string& me ) : me_( me ) {} bool ope
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;
}
“最烦人的解析”:
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;
}
#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;
}
calling operator()
calling operator()
before most vexing parse
after most vexing parse
calling operator()