指向类数据成员的指针“:*”我偶然发现了一个奇怪的代码片段,它编译得很好:class Car{
public:
int speed;};int main(){
int Car::*pSpeed = &Car::speed;
return 0;}为什么C+是否有指向类的非静态数据成员的指针?什么这个奇怪的指针在实际代码中使用吗?
3 回答
![?](http://img1.sycdn.imooc.com/54585094000184e602200220-100-100.jpg)
哔哔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;}
![?](http://img1.sycdn.imooc.com/5458506b0001de5502200220-100-100.jpg)
拉莫斯之舞
TA贡献1820条经验 获得超10个赞
// 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);}
- 3 回答
- 0 关注
- 678 浏览
添加回答
举报
0/150
提交
取消