3

我将以下内容放入 Ideone.com(和 codepad.org):

#include <iostream>
#include <string>
#include <tr1/functional>
 
struct A {
    A(const std::string& n) : name_(n) {}
    void printit(const std::string& s) 
    {
        std::cout << name_ << " says " << s << std::endl;
    }
private:
    const std::string name_;
};
 
int main()
{
    A a("Joe");
    std::tr1::function<void(const std::string&)> f = std::tr1::bind(&A::printit, &a, _1);
    a("Hi");
}

并得到这些错误:

prog.cpp:在函数'int main()'中:

prog.cpp:18: 错误: '_1' 未在此范围内声明

prog.cpp:19: 错误:不匹配调用 '(A)(const char [3])'</p>

prog.cpp:18:警告:未使用的变量“f”</p>

我一生都无法弄清楚第 18 行出了什么问题。

4

2 回答 2

7

两个错误:

  1. _1在命名空间中定义std::tr1::placeholders。您需要在using namespace std::tr1::placeholders; main()或使用std::tr1::placeholders::_1.

  2. 第 19 行应该是f("Hi"),不是a("Hi")

#include <iostream>
#include <string>
#include <tr1/functional>

struct A {
    A(const std::string& n) : name_(n) {}
    void printit(const std::string& s) 
    {
        std::cout << name_ << " says " << s << std::endl;
    }
private:
    const std::string name_;
};

int main()
{
    using namespace std::tr1::placeholders;  // <-------

    A a("Joe");
    std::tr1::function<void(const std::string&)> f = std::tr1::bind(&A::printit, &a, _1);
    f("Hi");    // <---------
}
于 2012-06-28T18:42:53.650 回答
5
于 2012-06-28T18:43:18.537 回答