2017-12-18 129 views
-7

我想了解C++中的委託。我讀到「代表團是功能指針」,我看到了幾個例子,但不幸的是我不能得到它。我已經創建了代碼來嘗試,因爲我認爲可能在編程時我會理解它。不幸的是我沒有。C++中的委託代碼

#include <iostream> 
using namespace std; 

class person{ 
    private: 
     int age; 
    public: 
     person(age){ 
      this->age = age; 
     } 

     // virtual void changeAge(int arg) = 0; 
}; 

class addNumber { 
    public: 
     int changeAge(int arg) { 
      arg += arg+1; 
     } 
}; 

int main(){ 
    person Olaf; 
} 

所以在此基礎上source我想:

Olaf = &addNumber::changeAge(10); 

addNumber test; 

Olaf = &addNumber::changeAge(10); 

兩個不起作用。這意味着程序不會編譯。 想使人對象使用addNumber類方法的changeName來改變實例人類的年齡。

+1

*「...我讀到」代表團是指向函數的指針「...」* - 你在哪裏讀到的? – WhiZTiM

+1

你的問題是什麼? – EvilTeach

+0

請定義你的意思是「_Both不工作。」 –

回答

1

首先,讓我們使用一個typedef的功能:

typedef int agechanger(int); 

這使得一個新的類型,agechanger,這將在代碼中用於傳遞左右的功能情況。

現在,你應該給你的person類正確的構造函數,並妥善包裝提供公共getter的age字段。然後添加一個接受函數作爲參數的方法,當然,類型爲agechanger的函數。

class person 
{ 
private: 
    int age; 
public: 
    person(int age){ 
     this->age = age; 
    } 

    int getAge() const { 
     return age; 
    } 
    void changeAge(agechanger f) 
    { 
     age = f(age); 
    } 
}; 

然後定義適合我們類型的函數,一個class內:

class addNumber { 
public: 
    static int changeAge(int arg) { 
     return arg + 1; 
    } 
}; 

注意,函數被標記爲static和返回傳入int遞增。

讓我們來測試一切都在一個main

int main() 
{ 
    person Olaf(100); //instance of person, the old Olaf 

    Olaf.changeAge(addNumber::changeAge); //pass the function to the person method 

    std::cout << Olaf.getAge() << std::endl; //Olaf should be even older, now 
} 

讓我們和使用不同的功能,ouside一類,這一次:

int younger(int age) 
{ 
    return age -10; 
} 

int main(){ 

    person Olaf(100); 

    Olaf.changeAge(younger); 

    std::cout << Olaf.getAge() << std::endl; // Olaf is much younger now! 
} 

我希望具有的工作原理是將代碼幫助你更好地理解事物。你在這裏提出的主題通常被認爲是先進的,而我認爲你應該先回顧一些更基本的C++主題(例如functionsclasses)。