指向類數(shù)據(jù)成員的指針“:*”我偶然發(fā)現(xiàn)了一個奇怪的代碼片段,它編譯得很好:class Car{
public:
int speed;};int main(){
int Car::*pSpeed = &Car::speed;
return 0;}為什么C+是否有指向類的非靜態(tài)數(shù)據(jù)成員的指針?什么這個奇怪的指針在實際代碼中使用嗎?
3 回答

嗶嗶one
TA貢獻1854條經(jīng)驗 獲得超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;}

拉莫斯之舞
TA貢獻1820條經(jīng)驗 獲得超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 關(guān)注
- 694 瀏覽
添加回答
舉報
0/150
提交
取消