请启发以下C++语法及其意义!(可能是过载的情况)

Please enlighten on the following C++ Syntax and its sense! (probably a case of overloading)

本文关键字:情况 C++ 语法      更新时间:2023-10-16

我正在研究一个遗留问题,发现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??

其中CCD_ 1是上面声明的CCD_ 2类的实例。

如上所述,有人能向我解释一下声明吗,比如:

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

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

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
thread_shared中的text2html是一个所谓的函数指针。然后将该指针分配给函数text2html。

c0是指向以std::string const &为参数的函数的指针的声明,并返回std::string

c.text2html = text2html使用函数text2html 初始化该指针

这里发生了名称冲突: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;