Pointer to class data member “::*”

后端 未结 15 1653
清歌不尽
清歌不尽 2020-11-21 11:47

I came across this strange code snippet which compiles fine:

class Car
{
    public:
    int speed;
};

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


        
15条回答
  •  悲哀的现实
    2020-11-21 12:14

    This is the simplest example I can think of that conveys the rare cases where this feature is pertinent:

    #include 
    
    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;
    }
    

    The thing to note here is the pointer passed in to count_fruit. This saves you having to write separate count_apples and count_oranges functions.

提交回复
热议问题