Delegation in C++

Delegation in C++

本文关键字:C++ in Delegation      更新时间:2023-10-16

我试图了解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;
}

因此,我尝试的基于此消息来源:

Olaf = &addNumber::changeAge(10);

addNumber test;
Olaf = &addNumber::changeAge(10);

两者都不起作用。这意味着程序没有编译。我想让个人对象使用addNumber类方法的changeName来更改实例人的年龄。

首先,让我们使用typedef来函数:

typedef int agechanger(int);

这是一种新类型的agechanger,该类型将用于代码传递函数实例。

现在,您应该给您的person类适当的构造函数,并适当地拆除age字段提供公共Getter。然后添加一种接受函数作为参数的方法,当然是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;
    }
};

请注意,该函数被标记为静态,并返回传递的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
}

让我们制作和使用不同的功能,这次是一个类:

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 的一些基本主题(例如,功能和类)。

在C 11中,后来您有封闭(例如thru std::function等...)和lambda表达式(即匿名函数)

但是,即使您还对成员函数的功能和指针也有指示,您也没有C 的委派。但是封闭和lambda表达在表达的力量上几乎等效。

您应该阅读SICP,然后阅读一些良好的C 编程书来理解这些概念。