Skip to content

Latest commit

 

History

History
54 lines (43 loc) · 1.06 KB

141 - 指向类成员的指针.md

File metadata and controls

54 lines (43 loc) · 1.06 KB

https://stackoverflow.com/questions/670734/pointer-to-class-data-member

问题

class Car
{
    public:
    int speed;
};

int main()
{
    int Car::*pSpeed = &Car::speed;
    return 0;
}

为什么这个指针要指向一个非静态类成员?这种奇怪的用法有什么用?

回答

这其实是一个 pointer to member,看下面的例子你就明白了,

#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_fruit 的第三个参数,这样就省去了单独编写 count_apples 和 count_oranges 函数的麻烦。