当调用指向数据成员的指针时会发生什么

发布于 2025-02-03 20:14:19 字数 845 浏览 1 评论 0原文

来自 cppreference ,我发现

数据成员的指针是可召唤的,即使没有进行函数调用。

但是,当我测试以下代码时,

#include <iostream>
#include <functional>
using namespace std;
class CTest
{
public:
    CTest() : n(0) {}
    ~CTest() {}
public:
    int n;
};

int main() {
    CTest o;
    auto f = std::bind(&CTest::n, o);
    f(1) = 2;
    cout << f() << endl;
    return 0;
}

我发现可以使用任何参数调用f,而不受计数或类型的限制。

那么,为什么我可以将几乎任何东西插入f(...)中?是语法喜欢吗

template<class... Args>
int f(Args&&... args) {
    return *pointer_to_data;
}

From Cppreference, I found it noted that

Pointers to data members are Callable, even though no function calls take place.

However, when I test following code

#include <iostream>
#include <functional>
using namespace std;
class CTest
{
public:
    CTest() : n(0) {}
    ~CTest() {}
public:
    int n;
};

int main() {
    CTest o;
    auto f = std::bind(&CTest::n, o);
    f(1) = 2;
    cout << f() << endl;
    return 0;
}

I found that I can call f with any arguments, not limited by count or type.

So, why can I insert almost any thing into f(...)? Is the syntax like

template<class... Args>
int f(Args&&... args) {
    return *pointer_to_data;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文