无法理解c++中处理程序的概念

Unable to understand this concept of handlers in c++

本文关键字:程序 处理 c++      更新时间:2023-10-16

我正在编写一段代码,突然发现了一些新的东西。然而,为了更好地理解,我尝试编写自己的代码。

#include<iostream>
using namespace std;
class material
{
public:
material()
{
    cout<<"material() called"<<endl;
}
bool test_func()
{
    cout<<"Hello World"<<endl;
    return true;
}
};
class server
{
private:
material *mat;
public:
server()
{
    cout<<"server() called"<<endl;
}
material *matrl()
{
    return mat;
}
};
class Handler
{
public:
Handler()
{
    cout<<"Handler() called"<<endl;
}
server svr;
bool demo()
{
    bool ret;
    ret=svr.matrl()->test_func();
    return ret;
}
};
int main()
{
Handler h;
cout<<"returned by demo():"<<h.demo()<<endl;
return 0;
}

甚至我也得到了想要的输出,那就是:

server() called
Handler() called
Hello World
returned by demo():1

但我无法理解这里的某些概念:

material *matrl()
{
    return mat;
}

函数调用

ret=svr.matrl()->test_func();

这是如何运作的,这背后的概念是什么?有人能帮我吗???

如果重写,可以避免混淆

material *matrl()
{
    return mat;
}

material* matrl()
{
    return mat;
}

两者都一样。这是一个返回指向材料类型对象的指针的函数

现在

ret=svr.matrl()->test_func();

因为CCD_ 1返回一个指向成员函数需要使用->的对象的指针。或者
*(svr.matr1()).test_func();