Delegation in C++
Delegation in 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;
}
因此,我尝试的基于此消息来源:
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 编程书来理解这些概念。
相关文章:
- netcat command in c++
- Difference in displaying cv2 Mat
- C++ MFC Libraries in Travis CI
- 如何在OpenSSL中从configuration.h.in获取configuration.h
- 创建具有 new in 函数和"this is nullptr"异常的对象
- IN, OUT, INOUT Parameters
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 有人安装"IITB Simplecpp in mac"吗?
- 从 C 样式字符串中删除子字符串 "in place" 在C++代码中
- 如何修复"error: ‘_1’ was not declared in this scope"?
- Softmax Implementation in C++
- 将 out/in out 参数与 if/switch 的 init 语句一起使用
- IF-nesting in c++
- Gurobi GRBModel and GRBmodel in C++
- Tensorflow Hub in C++
- Centos7 g++ "to_string is not in a member of std"
- InitializeCriticalSectionEx Not Located In KERNEL32.Dll
- 将 lambda 表达式传递给 std::function in C++
- @CPPFLAGS@在 Makefile.in 中意味着什么?
- std::async from std::async in windows xp