头中编码与cpp中编码:不同的行为
Coding in header vs coding in cpp: different behaviour
我发现有些代码除非在头文件本身上声明,否则无法工作。例如,使用以下代码,当调用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");
};
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- Linux的Cpp上的计时器
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 内置函数可查看CPP中的成员变量
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- Cpp-Tuple使用带有变量的get
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 有充分的理由在h文件中使用include保护而不是cpp文件吗
- 如何通过cpp程序运行shell脚本
- 如何在CPP的给定目录中列出UTF编码的文件名?
- YAML-CPP 编码/解码指针?
- 尝试用C++编码时,我收到一长串错误,例如"/tmp/ccloHU4h.o:dad.cpp:(.text+0x5c): undefined reference to `std::cout'"
- 何时使用多个CPP文件(良好的编码实践)
- LIBAV视频编码速率控制.cpp:766.
- 编码C++(大部分)在头文件与.cpp文件中
- 头中编码与cpp中编码:不同的行为
- 如何读取UTF-8编码与cpp-netlib时,没有指定在html头