gpt4 book ai didi

c++ - 在类中存储 typedef 构造函数

转载 作者:行者123 更新时间:2023-11-30 05:07:38 25 4
gpt4 key购买 nike

我想弄清楚在我的类中存储一个 typedef,我该怎么做?在发布的示例中,我想创建一个类,它允许我启动多个具有不同“Fct”参数的对象,例如“one”或“slope”,甚至可以使用 set 函数更改对象的“Fct f”:

typedef double Fct(double);

double one(double x) { return 1; }
double slope(double x) { return x / 2; }

struct myFct : Shape {
myFct(Fct f)
:f(f) {}; //"f" is not a nonstatic data member of base class of class "myFct"

private:
Fct f;
};

最佳答案

您的typedef 代表一个函数类型。 typedef 可用于声明成员函数。所以您的类有一个成员函数f 声明。它接受一个 double 并返回一个 double 。

我怀疑您想要的是作为成员变量 的函数指针。明确地做:

struct myFct : Shape {
myFct(Fct *f)
:f(f) {}; //"f" is not a nonstatic data member of base class of class "myFct"

private:
Fct *f;
};

您可能认为自己很幸运,偶然发现了一个有点晦涩的功能。

关于c++ - 在类中存储 typedef 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47328156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com