头中编码与cpp中编码:不同的行为

Coding in header vs coding in cpp: different behaviour

本文关键字:编码 cpp      更新时间:2023-10-16

我发现有些代码除非在头文件本身上声明,否则无法工作。例如,使用以下代码,当调用test()时,将打印"Hello World":

//Myclass.h
class Myclass {
private:
    SoftwareSerial *ss;
public:
    void test() {
        ss = & SoftwareSerial(0,1);
        ss->begin(9600);
        ss->print("Hello World");;
    };
};

但是,如果我只是在头上声明方法test(),并像往常一样在一个单独的cpp上用完全相同的代码对其进行编码,它会编译但不会输出任何内容:

//Myclass.cpp
void Myclass::test(){
    ss = & SoftwareSerial(0,1);
    ss->begin(9600);
    ss->print("Hello World");
 };
 //this won't output anything

为什么?

SoftwareSerial是一种类型。你正在获取一个指向临时对象的指针,然后在临时对象终止后取消引用它。这是非法的;我不知道你的编译器为什么接受它,但我要冒险指出,这并不意味着它在做你认为的事情。它可能会破坏一些东西,并导致奇怪的行为,试图合理化这些行为是愚蠢的。

相反:

//Myclass.h
class Myclass {
private:
    SoftwareSerial ss;
public:
    Myclass();
    void test();
};

//Myclass.cpp
Myclass::Myclass() : ss(0,1) {};
void Myclass::test() {
    ss.begin(9600);
    ss.print("Hello World");
};