从父类定义中调用学生方法

问题描述 投票:0回答:1

我正在制作 LCD 菜单,但在

lcdmenu
(主菜单)和
submenu
交互方面遇到问题。

class submenu;

class lcdmenu
{
protected:
    command **commandlist;
    submenu **submenulist;
    ...   

public:
    void setchildren(command **comlist, submenu **sublist, int comn, int subn);
    void render();
    ...

};

void lcdmenu::render(){
    lcd_clear();
    for (int line = 0; line < MAX_LINES; line ++){
        int index = menutop + line;
        ...

        if (index < numcommands){
            lcd_string(commandlist[index]->get_text());
            lcd_string(submenulist[index]->get_text()); 
        }
class submenu : public lcdmenu {
public:
    lcdmenu *parent;
    submenu(lcdmenu *par, const char* text);

    const char* get_text(){
        return text;
    }
};

submenu::submenu(lcdmenu *par, const char* text_):text(text_), parent(par)
{
}

我将

submenu
实例列表传递到
lcdmenu.submenulist
变量中,并且我希望
lcdmenu::render()
调用
lcd_string(submenulist[index]->get_text());
,但当该方法尚未定义时,我无法使用
submenu.get_text

有没有办法格式化我的文件,以便我可以在彼此之间使用完全定义的

lcdmenu
类和
submenu
类?

c++ class oop inheritance raspberry-pi-pico
1个回答
0
投票

在声明方法之前,您根本无法使用该方法。

lcdmenu::submenulist
成员使用前向声明是完全可以的,但对于
lcdmenu::render()
方法的实现来说就不行了。 您需要完整的
submenu
类声明才能调用
submenu::get_text()
。 因此,您需要将代码分成
.h
.cpp
文件以方便实现此目的,例如:

lcdmenu.h

#ifndef lcdmenu_H
#define lcdmenu_H

class command;
class submenu;

class lcdmenu
{
protected:
    command **commandlist;
    submenu **submenulist;
    ...   

public:
    void setchildren(command **comlist, submenu **sublist, int comn, int subn);
    void render();
    ...
};

#endif

lcdmenu.cpp

#include "lcdmenu.h"
#include "command.h"
#include "submenu.h"
...

void lcdmenu::render(){
    lcd_clear();
    for (int line = 0; line < MAX_LINES; line ++){
        int index = menutop + line;
        ...

        if (index < numcommands){
            lcd_string(commandlist[index]->get_text());
            lcd_string(submenulist[index]->get_text()); 
        }

子菜单.h

#ifndef submenu_H
#define submenu_H

#include "lcdmenu.h"

class submenu : public lcdmenu {
public:
    lcdmenu *parent;
    submenu(lcdmenu *par, const char* text);

    const char* get_text();
};

#endif

子菜单.cpp

#include "submenu.h"

submenu::submenu(lcdmenu *par, const char* text_):text(text_), parent(par)
{
}

const char* submenu::get_text(){
    return text;
}
© www.soinside.com 2019 - 2024. All rights reserved.