运算符->*是什么意思?

2023-05-28 0 281

的提问有严重错误,他而已在说明 -> 操作符和 * 操作符。

但在 C++ 中,除三种操作符,即使再次出现频度不多而不被我们所津津乐道,她们是 .* 操作符和 ->* 操作符,被泛称做核心成员操作符出访操作符。

具体来说,他们须要晓得,在 C++ 中,除他们原本在 C 中所津津乐道的通常操作符 (用作则表示第一类的门牌号的操作符)外,除两类操作符,称作对准类核心成员的操作符。而对准类核心成员的操作符又拆成两类。两类是对准类的统计数据成的操作符,它通常用作则表示某两类的某一核心成员相对于类的封土的差值;除两类是对准类的非动态核心成员方式的操作符,它可等效 C 中的表达式操作符,或者说虽然类的非typename较之通常表达式和类的typename,要显式地多接收两个 this 模块,因此她们的类别与通常表达式相同,须要两类捷伊操作符类别来则表示。

先上标识符:

#include <iostream> struct Foo { int x; int y; }; void test(Foo & ref, int Foo::* ptr_to_member) { std::cout << ref.*ptr_to_member << std::endl; } void test(Foo * ptr, int Foo::* ptr_to_member) { std::cout << ptr->*ptr_to_member << std::endl; } int main() { Foo f; f.x = 3; f.y = 4; test(f, &Foo::x); test(f, &Foo::y); test(&f, &Foo::x); test(&f, &Foo::y); return 0; }

上例演示了 .* 操作符和 ->* 操作符配合对准类的统计数据核心成员操作符的使用方式。&Foo::x, &Foo::y 等计算出了 Foo 类的 x, y 分量相对封土的差值,而 test 表达式则根据 f 第一类的引用或者门牌号加上所传的差值得到最终的统计数据。

而对于下例,对准类的非动态核心成员表达式的操作符的用法,则是换汤不换药:

#include <iostream> struct Foo { void f() const { std::cout << “f” << std::endl; } void g() const { std::cout << “g” << std::endl; } }; void test(Foo & ref, void (Foo::* ptr_to_member_fn)() const) { (ref.*ptr_to_member_fn)(); } void test(Foo * ptr, void (Foo::* ptr_to_member_fn)() const) { (ptr->*ptr_to_member_fn)(); } int main() { Foo f; test(f, &Foo::f); test(f, &Foo::g); test(&f, &Foo::f); test(&f, &Foo::g); return 0; }

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务