You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

类中引用指针对象报错:Adafruit_SPITFT引用无法初始化Adafruit_ST7789指针

类中调用Adafruit库drawBMP方法报错

错误信息

_reader->drawBMP("/background.bmp", _tft, 0, 0);

a reference of type "Adafruit_SPITFT &" (not const-qualified) cannot be initialized with a value of type "Adafruit_ST7789 *"

问题场景

相同代码在类外可正常运行,但封装到Info类中触发上述错误,相关代码如下:

Main.cpp

SdFat SD;                        // SD卡文件系统
Adafruit_ImageReader reader(SD); // 图像读取对象,传入SD文件系统
Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);
Info info(&tft, &reader, debug);

Info.h

#ifndef INFO_H
#define INFO_H

#include <Adafruit_GFX.h> // 核心图形库
#include <Adafruit_ST7789.h>
#include <SdFat.h>                // SD卡与FAT文件系统库
#include <Adafruit_SPIFlash.h>    // SPI/QSPI闪存库
#include <Adafruit_ImageReader.h> // 图像读取函数库

class Info {
    public:
        Info(Adafruit_ST7789 *tft, Adafruit_ImageReader *reader, bool debug);
        void GenerateInfo();
    private:
        Adafruit_ST7789 *_tft;
        Adafruit_ImageReader *_reader;
        bool _debug;
};

#endif // INFO_H

Info.cpp

#include "Info.h"
#include <Arduino.h> // 按需引入Arduino库

Info::Info(Adafruit_ST7789 *tft, Adafruit_ImageReader *reader, bool debug)
{
    _tft = tft;
    _reader = reader;
    _debug = debug;
}

void Info::GenerateInfo()
{
    // 绘制背景图
    _reader->drawBMP("/background.bmp", _tft, 0, 0);
}

解决方案

修改Info.cpp中GenerateInfo方法的调用代码,将指针_tft解引用为对象引用:

void Info::GenerateInfo()
{
    // 绘制背景图
    _reader->drawBMP("/background.bmp", *_tft, 0, 0);
}

原因说明

Adafruit_ImageReader的drawBMP方法第二个参数要求是Adafruit_SPITFT&类型的引用,而Info类中存储的_tft是指针类型(Adafruit_ST7789*),直接传递指针会导致类型不匹配,触发编译错误。

类外调用时直接传递tft对象,编译器会自动将其转换为对应的引用,因此可以正常运行;而类中需要显式对指针进行解引用(*_tft),得到对象的引用后再传递给方法,即可解决类型不匹配问题。

内容的提问来源于stack exchange,提问作者user2570937

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 07:16:01