【发布时间】:2021-08-02 21:10:12
【问题描述】:
我有一个继承自其他类的结构 A(我不允许更改)。在 A 和它的方法中,我可以毫无问题地调用继承的方法(比如说 A_method(int i))但是当我尝试编写一个嵌套结构(比如说 In)并调用 A_method(int i) 并且有我卡住了。
初始代码是这样的,我无法更改,是某种大学作业。
#include "Player.hh"
struct A : public Player {
static Player* factory () {
return new A;
}
virtual void play () {
}
};
RegisterPlayer(PLAYER_NAME);
然后我尝试了这个:
#include "Player.hh"
struct A : public Player {
static Player* factory () {
return new A;
}
//My code
struct In {
int x;
void do_smthing() {
A_method(x);
}
}
virtual void play () {
}
};
RegisterPlayer(PLAYER_NAME);
好的,从一开始我就知道我不能这样做,因为 In 要查看它的父类,它应该有一个指向它的指针,但 In 是我的代码中经常实例化的对象,我想避免传递 this不断给构造函数,所以我尝试了这种方法:
#include "Player.hh"
struct A : public Player {
static Player* factory () {
return new A;
}
//My code
static struct Aux
A* ptr;
Aux(A* _p) { ptr = _p; }
} aux;
struct In {
int x;
void do_smthing() {
aux.ptr->A_method(x);
}
}
virtual void play () {
//the idea is to call do_smthing() here.
}
};
RegisterPlayer(PLAYER_NAME);
我想避免的(如果可能的话)是这样的:
struct In {
int x;
A* ptr;
In (A* _p) : ptr(_p) {}
void do_smthing() {
ptr->A_method(x);
}
}
主要原因:我有更多的结构定义,它们通过其余的(省略的)代码多次实例化,我不喜欢看到In(this)这么多次的想法。
我不知道我是否完全遗漏了某些东西,或者我想做的事情是不可能的……如有必要,请要求澄清。
(另外,性能很关键,我的代码将在有限的 CPU 时间下进行测试,所以我必须尽可能避免使用昂贵的方法。使用 C++11)
【问题讨论】:
-
另外,我真的不知道问题标题是否足够好地解决这个问题,我会感谢任何建议或版本。
标签: c++11 pointers inheritance struct multiple-inheritance