请指教以下C ++语法及其意义! (可能是超载的情况)

时间:2011-08-16 14:02:39

标签: c++ function pointers syntax overloading

我正在阅读遗产,并发现C ++的以下语法很奇怪:

类定义如下:

class thread_shared : public master
{
public:
    thread_shared() 
    {
        thread_id = 0;
    }
    int thread_id;
    std::string title;
    std::string (*text2html)(std::string const &);  // What's this declaration?

};

和text2html的定义为:

namespace {
    std::string text2html(std::string const &s)
    {
        std::string tmp=cppcms::util::escape(s);
        std::string res;
        res.reserve(tmp.size());
        for(unsigned i=0;i<tmp.size();i++) {
            if(tmp[i]=='\n') {
            res+="<br />";
            }
            res+=tmp[i];
        }
        return res;
    }
}

然后使用如下:

c.id = 1; // any integer
c.title = "some string";        
c.text2html = text2html;   // whats this??

其中c是上面声明的thread_shared类的实例。

如上所述,有人可以向我解释如下声明:

std::string (*text2html)(std::string const &);然后c.text2html = text2html;

上面的代码到底是做什么的?

4 个答案:

答案 0 :(得分:11)

std::string (*text2html)(std::string const &);  // What's this declaration?

这是一个函数指针定义。它声明变量text2html是指向具有签名std::string (std::string const &)的函数的指针。

c.text2html = text2html;   // whats this??

即设置指针以引用具有适当签名的text2html函数。右侧是一个函数标识符,并衰减为&text2html,在这种情况下,它会解析为未命名的命名空间中的地址。

请注意,您可以将其设置为具有相同签名的任何函数,名称的巧合只是巧合:

std::string foo( std::string const & ) {}
c.text2html = &foo;  // & optional

答案 1 :(得分:3)

thread_shared中的

text2html是一个所谓的函数指针。然后将此指针指定为指向函数 text2html。

答案 2 :(得分:3)

std::string (*text2html)(std::string const &);是指向函数的指针的声明,该函数以std::string const &为参数,并返回std::string

c.text2html = text2html使用函数text2html

初始化此指针

答案 3 :(得分:1)

你发生了名称冲突:text2html既被用作thread_shared类的字段名称,也被用作函数。

第一部分:

std::string (*text2html)(std::string const &);

在thread_master类上定义名为text2html的函数指针字段。具体来说,该字段是指向具有如下签名的函数的指针:

std::string foo(std::string const&);

该行

c.text2html = text2html

将第二个代码块中定义的text2html函数指定给c的'text2html'字段。

您可以轻松定义功能

std::string pants(std::string const& dude) { return dude + " has red pants";}

然后将其分配给c:

c.text2html = pants;