无法从父母中调用子女的功能

cannot call the function in child from the parent

本文关键字:功能 调用 父母      更新时间:2023-10-16

我正在使用qt Creator中的C 开发游戏。

我可以在没有问题的情况下在MAIN中调用子类的额定功能,但是当我尝试从父母课程中调用子类函数时,该程序会意外关闭。

我已经在父类的.h文件中声明了所有公共属性。t尝试将这些属性删除并将其放置在子类的.h文件中,然后效果很好。但是W想将它们保留在父班中并访问孩子班的班级。

请帮助使它工作,我尝试了几次,但我无法弄清楚。

.h父级文件:

class Game:public QGraphicsView,public home{
Q_OBJECT
public:
Game(QWidget* parent=0);
virtual ~Game(){}
void createBlockCol(double x);
void creatBlockGrid();
virtual void setbackground();
QPushButton *btn2;
QPushButton *btn3;
QPushButton *btn4;
QGraphicsScene* scene;
QGraphicsScene *scene2;
QGraphicsView* view;
QPushButton *btn;
QPushButton *btn1;
QGraphicsProxyWidget *pr;
QGraphicsProxyWidget *pr1;

QGraphicsProxyWidget *pr2;
QGraphicsProxyWidget *pr3;
QGraphicsProxyWidget *pr4;
QGraphicsPixmapItem* item1;
QGraphicsPixmapItem* item;
private slots:
void start();

这是.cpp类的父

Game::Game(QWidget *parent): QGraphicsView(parent){
scene = new QGraphicsScene(0,0,466,600);
setScene(scene);
}
void Game::setbackground(){
scene2 = new QGraphicsScene(0,0,400,600);
QGraphicsView* view = new QGraphicsView(scene2);
item = new QGraphicsPixmapItem(QPixmap(":/Ies/uu.jpg"));
scene2->addItem(item);
view->show();
game_function *gm; //call a function in child class
gm->set_buttons();
}

儿童类.h文件

class game_function:public Game
{
Q_OBJECT
public:
void set_background();
void mainwindow();
void set_buttons();

private slots:
void button_help();
};

.cpp文件

void game_function::set_buttons(){

btn = new QPushButton;
QObject::connect(btn,SIGNAL(clicked()),this,SLOT(startgame()));
btn->setStyleSheet("background-color: white");
pr = this->scene2->addWidget(button);
btn->setAutoFillBackground(true);
btn->setIcon(QIcon(":/Ies/main.png"));
btn->setIconSize(QSize(131,41));
pr->setPos(130,430);
btn1 = new QPushButton;
QObject::connect(btn1,SIGNAL(clicked()),this,SLOT(stopgame()));
btn1->setStyleSheet("background-color: white");
pro = this->scene2->addWidget(button1);
btn1->setAutoFillBackground(true);
btn1->setIcon(QIcon(":/Images/exit.png"));
btn1->setIconSize(QSize(131,41));
pr->setPos(130,500);

我可以称呼此功能

您可能与尝试多态性调用相距不远...

也许如果您

a)添加" game :: set_buttons()",使其变为虚拟,也许是纯虚拟的,在类标题中的某个地方:

class Game:public QGraphicsView,public home{
// ... perhaps after
virtual ~Game(){}
virtual void setbuttons() = 0;
// ...
} // end of class Game

然后,在方法" game :: setbackground()"中,您可以使用它...替换此

// undefined behavior - gm not initialized
//game_function *gm; //call a function in child class
//gm->set_buttons();

this->set_buttons();