【发布时间】:2019-02-04 12:13:14
【问题描述】:
我正在尝试使用来自不同类的类成员,将“class uart”添加到“class parser : public uart”
但是我不能在解析器类中使用成员变量,例如(缓冲区大小、缓冲区或状态枚举值没有改变或更新)我可以使用这些变量的唯一方法是将它们用作外部变量,但我会喜欢以班级成员的方式来做。
请在下面找到我的代码:
主要:
#include <stdio.h>
#include "parser.h"
int main()
{
parser m_parser;
m_parser.test();
return 0;
}
uart.h
#include <stdint.h>
#include <stdio.h>
//extern uint16_t buffer_size;
//extern char buffer[1024];
class uart
{
public:
// Construction
uart();
//..... some functions
void Initialize();
//members
enum STATE_enum
{
Buffering_message=0,
Message_received,
Buffering_empty
};
STATE_enum state;
uint16_t buffer_size;
char buffer[1024];
protected:
// static void UARTHandler(app_uart_evt_t * p_event);
void Message();
// Singleton instance
static uart * m_instance;
};
uart.cpp
#include "uart.h"
//uint16_t buffer_size=0;
//char buffer[1024];
uart * uart::m_instance = 0; // Singleton instance
uart::uart()// Construction
{
state = Buffering_empty;
m_instance = this;
}
void uart::Initialize()
{
}
/*void UART::UARTHandler(app_uart_evt_t * p_event)
{
Message();
}*/
void uart::Message()
{
uint8_t value;
// while ((app_uart_get(&value)) == NRF_SUCCESS) //specific function from my microcontroller stack for reading RX bytes
{
if(value == 0x0A ) // message end /r
state = Message_received;
}
switch (state)
{
case Message_received:
printf("message:[%s] buffer_size:[%d]", buffer,buffer_size); //printf fine from there
break;
case Buffering_message:
buffer[buffer_size++] = value;
break;
default:
break;
}
}
parser.h
#include <stdio.h>
#include <stdint.h>
#include "uart.h"
class parser : public uart
{
public:
parser();
void test();
static parser * m_instance;
static inline parser & Instance()// Singleton access
{
return *m_instance;
}
};
parser.cpp
#include "parser.h"
class parser * parser::m_instance = 0;
// Constructor
parser::parser()
{
m_instance = this;
}
void parser::test()
{
printf("state %s", state); // sending AT command
// memset(buffer, 0, buffer_size);
// buffer_size = 0;
}
我应该将上面的作为公共类使用还是添加为朋友类,或者只是用作外部变量?
【问题讨论】:
-
题外话:不要实现单例模式和提供公共构造函数!更好的变体(由标准保证甚至是线程安全的):
SC& instance() { static SC sc; return sc; } -
您在哪里尝试使用这些成员?我在
parser中看不到任何代码。您收到什么错误消息? -
当你说“我不能在解析器类中使用成员变量”时,那是什么意思 exactly ?编译器是否无法摄取您的代码?编译成功后运行代码有没有报错? Fwiw,这不是一个正确的单例模式(如果有的话),但不知何故,我认为这与你真正遇到的任何问题无关。即使这个编译
buffer_size是不确定的,所以memset调用是运行时错误的秘诀。 -
因为
parser继承自uart,所以创建parser对象最终会在两个单例中指向同一个实例,丢失之前可能创建的单独uart单例对象!这是你想要的吗? -
很容易忽略
%s问题,因为您的示例不是最小的。看看minimal reproducible example。您应该删除与错误无关的所有部分。迭代步骤:删除部分代码,测试问题是否仍然存在,如果仍然存在,则继续,否则保留刚刚删除的代码部分。您可能会从整个类开始,完成后,剩下的类的功能,最后是功能块......在这个过程中,您很可能已经自己发现了问题(但很可能,在特定情况下不是......) .