是否可以从 C++ 中此 class 中定义的结构内部调用 class 方法?
Is possible to call a class method from inside of struct defined within this class in C++?
我有一个父项 class、一个子项 class 并且在这个子项中 class 我已经定义了一些结构。在这个结构中,我想调用父方法。可能吗?
class Parent
{
public:
int foo(int x);
}
class Child : public Parent
{
public:
struct ChildStruct {
int x;
int bar(int y) {
return GET_CLASS_CHILD->foo(this->x + y);
}
};
}
在 C++ 中可以实现这样的功能吗?那怎么实现呢?
您必须向 ChildStruct
传递指向所有者 class 实例的引用或指针:
class Child : public Parent
{
public:
struct ChildStruct {
int x;
Child& owner;
ChildStruct(Child& owner_) : owner(owner_) {}
int bar(int y) {
return owner.foo(this->x + y);
}
};
};
也就是说,看起来您真正需要的是 lambda function。
我有一个父项 class、一个子项 class 并且在这个子项中 class 我已经定义了一些结构。在这个结构中,我想调用父方法。可能吗?
class Parent
{
public:
int foo(int x);
}
class Child : public Parent
{
public:
struct ChildStruct {
int x;
int bar(int y) {
return GET_CLASS_CHILD->foo(this->x + y);
}
};
}
在 C++ 中可以实现这样的功能吗?那怎么实现呢?
您必须向 ChildStruct
传递指向所有者 class 实例的引用或指针:
class Child : public Parent
{
public:
struct ChildStruct {
int x;
Child& owner;
ChildStruct(Child& owner_) : owner(owner_) {}
int bar(int y) {
return owner.foo(this->x + y);
}
};
};
也就是说,看起来您真正需要的是 lambda function。