指向类成员的指针

2022-02-10 19:13:02 浏览数 (2)

问题

代码语言:javascript复制
class Car
{
    public:
    int speed;
};

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

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

回答

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

代码语言:javascript复制
#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) << " applesn";
    std::cout << "I have " << count_fruit(bowls, bowls   2, & bowl::oranges) << " orangesn";
    return 0;
}

关注点在于 count_fruit 的第三个参数,这样就省去了单独编写 count_apples 和 count_oranges 函数的麻烦。

0 人点赞