为了账号安全,请及时绑定邮箱和手机立即绑定

指向类数据成员的指针“:*”

指向类数据成员的指针“:*”

C++ C
慕虎7371278 2019-06-10 20:53:13
指向类数据成员的指针“:*”我偶然发现了一个奇怪的代码片段,它编译得很好:class Car{     public:     int speed;};int main(){     int Car::*pSpeed = &Car::speed;     return 0;}为什么C+是否有指向类的非静态数据成员的指针?什么这个奇怪的指针在实际代码中使用吗?
查看完整描述

3 回答

?
哔哔one

TA贡献1854条经验 获得超8个赞

这是我能想到的最简单的例子,它传达了这种特性相关的罕见情况:

#include <iostream>class bowl {public:
    int apples;
    int oranges;};int count_fruit(bowl * begin, bowl * end, int bowl::*fruit){
    int count = 0;
    for (bowl * iterator = begin; iterator != end; ++ iterator)
        count += iterator->*fruit;
    return count;}int main(){
    bowl bowls[2] = {
        { 1, 2 },
        { 3, 5 }
    };
    std::cout << "I have " << count_fruit(bowls, bowls + 2, & bowl::apples) << " apples\n";
    std::cout << "I have " << count_fruit(bowls, bowls + 2, & bowl::oranges) << " oranges\n";
    return 0;}

这里要注意的是传入用于计数_水果的指针。这就省去了编写单独的count_apples和count_橙子函数的麻烦。


查看完整回答
反对 回复 2019-06-10
?
拉莫斯之舞

TA贡献1820条经验 获得超10个赞

另一个应用程序是侵入列表。元素类型可以告诉列表下一个/prev指针是什么。因此,列表不使用硬编码名称,但仍然可以使用现有指针:

// say this is some existing structure. And we want to use// a list. We can tell it that the next pointer// is apple::next.struct apple {
    int data;
    apple * next;};// simple example of a minimal intrusive list. Could specify the// member pointer as template argument too, if we wanted:
    // template<typename E, E *E::*next_ptr>template<typename E>struct List {
    List(E *E::*next_ptr):head(0), next_ptr(next_ptr) { }

    void add(E &e) {
        // access its next pointer by the member pointer
        e.*next_ptr = head;
        head = &e;
    }

    E * head;
    E *E::*next_ptr;};int main() {
    List<apple> lst(&apple::next);

    apple a;
    lst.add(a);}


查看完整回答
反对 回复 2019-06-10
  • 3 回答
  • 0 关注
  • 678 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信