请启发以下C++语法及其意义!(可能是过载的情况)
Please enlighten on the following C++ Syntax and its sense! (probably a case of 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??
其中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
text2html
是一个所谓的函数指针。然后将该指针分配给函数text2html。
c
0是指向以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;
- 在没有太多条件句的情况下,我如何避免被零除
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 函数中堆分配的效果与缺少堆分配的情况
- 在未初始化映射的情况下,将值插入到映射的映射中
- 是默认情况下分配给char数组常量的值
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 如何在不产生任何垃圾的情况下获得C中的像素
- 在已经使用Git的情况下减少编译时间
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- 如何在没有信号的情况下从C++执行QML插槽
- 如何在不知道向量大小的情况下输入向量内部的向量?
- 如何针对特定情况调试和修复此双自由内存损坏问题
- 为什么在某些情况下不写入此文件?
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 在没有Xcode的情况下在Mac捆绑包中嵌入框架
- 有没有一种方法可以测量c++程序的运行时内存使用情况
- UE4-如何在给定4个屏幕坐标的情况下缩放纹理或材质
- 为什么这个音频包络不能通过开关的情况?
- 为什么需要复制构造函数,在哪些情况下它们非常有用
- 在C++中如何在没有pow的情况下进行基础计算