繁体   English   中英

指向 object 的指针的 function 的别名

[英]Alias for a function of a pointer to an object

我正在使用单独的 map class 和单独的渲染器 class 制作游戏,用于渲染 Z1D78DC8ED51214E5018B511FE

这是一个简化版本:(我感兴趣的 function 是renderMap()

#include <iostream>
#include <vector>

class Map
{
public:
    Map(int mapSize)
        : data(mapSize,3) {} //Initialize the vector with the requested size, filled with 3's. Just as an example

    //Accessors
    const std::vector<int>& accessData() { return data; }

private:
    std::vector<int> data;
};

class Renderer
{
public:
    void setPointerToMap(Map& map) { pointerToMap = &map; }

    void renderMap()
    {
        // Here some of the calls to the map object might become really long, especially if the vector "data" contains objects and we need to access the objects
        // So can we somehow create a short alias for "pointerToMap->accessData()"?
        // So that instead of "pointerToMap->accessData()[0]" we write "dataPoint[0], for example

        std::cout << pointerToMap->accessData()[0];
    }
private:
    Map* pointerToMap;
};

int main()
{
    Map map(5);  // Create map object

    Renderer renderer;  // Create renderer object

    renderer.setPointerToMap(map);   // "Attach" the map to the renderer by giving the renderer a pointer to the map

    renderer.renderMap();  // Render the map in the renderer using the pointer to the map to read the data
}

所以基本上我使用指向map object 的指针在渲染器中读取 Map 的数据。 我已经阅读了有关using关键字和 function 指针的信息,但无法确定它们是否打算用于此目的。

我试着像这样制作一个 function 指针:

std::vector<int>& (Map:: * dataPoint)() = pointerToMap->accessData;

但这给出了一个错误error C3867: 'Map::accessData': non-standard syntax; use '&' to create a pointer to member error C3867: 'Map::accessData': non-standard syntax; use '&' to create a pointer to member and Visual Studio says that "a pointer to a bound function may only be used to call the function. So I guess it is simply not possible to create a function pointer if we access the function with指针?

如果我们公开data向量,那么我们可以访问它:

std::vector<int>& dataPoint = pointerToMap->data;
std::cout << dataPoint[0];

但这并不是我在实际游戏中所需要的。

奖励:这是我设法在renderMap()中创建 function 指针的另一种方式,但我不明白它是如何工作的,而且它并不能真正正常工作:

std::vector<int>& (Map:: * dataPoint)() = &Map::accessData;
std::cout << dataPoint;

所以问题是,在这种情况下是否可以缩短 function 调用以及如何缩短调用?

无需在每一行上调用accessData ,只需创建一个引用并将其用于所有其他行:

const std::vector<int>& dataPoint = pointerToMap->accessData();

std::cout << dataPoint[0];

在这里,您创建一个新变量,它是对accessData返回的向量的引用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM