无法从父级调用子级中的函数

时间:2017-12-07 11:06:46

标签: c++ qt

我正在Qt创建者中使用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);

1 个答案:

答案 0 :(得分:2)

  

我可以通过这种方式调用此功能

您尝试多态调用可能不会太远......

也许如果你

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();
相关问题