第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

指向類數(shù)據(jù)成員的指針“:*”

指向類數(shù)據(jù)成員的指針“:*”

C++ C
慕虎7371278 2019-06-10 20:53:13
指向類數(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個贊

這是我能想到的最簡單的例子,它傳達了這種特性相關(guān)的罕見情況:

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

這里要注意的是傳入用于計數(shù)_水果的指針。這就省去了編寫單獨的count_apples和count_橙子函數(shù)的麻煩。


查看完整回答
反對 回復(fù) 2019-06-10
?
拉莫斯之舞

TA貢獻1820條經(jīng)驗 獲得超10個贊

另一個應(yīng)用程序是侵入列表。元素類型可以告訴列表下一個/prev指針是什么。因此,列表不使用硬編碼名稱,但仍然可以使用現(xiàn)有指針:

// 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);}


查看完整回答
反對 回復(fù) 2019-06-10
  • 3 回答
  • 0 關(guān)注
  • 694 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號