Pointer to class data member “::*”

后端 未结 15 1637
清歌不尽
清歌不尽 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:23

    It makes it possible to bind member variables and functions in the uniform manner. The following is example with your Car class. More common usage would be binding std::pair::first and ::second when using in STL algorithms and Boost on a map.

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    
    class Car {
    public:
        Car(int s): speed(s) {}
        void drive() {
            std::cout << "Driving at " << speed << " km/h" << std::endl;
        }
        int speed;
    };
    
    int main() {
    
        using namespace std;
        using namespace boost::lambda;
    
        list l;
        l.push_back(Car(10));
        l.push_back(Car(140));
        l.push_back(Car(130));
        l.push_back(Car(60));
    
        // Speeding cars
        list s;
    
        // Binding a value to a member variable.
        // Find all cars with speed over 60 km/h.
        remove_copy_if(l.begin(), l.end(),
                       back_inserter(s),
                       bind(&Car::speed, _1) <= 60);
    
        // Binding a value to a member function.
        // Call a function on each car.
        for_each(s.begin(), s.end(), bind(&Car::drive, _1));
    
        return 0;
    }
    

提交回复
热议问题