当成员是用户定义的类时,如何编写正确的类定义和声明?
How do I write a proper class definition & declaration when a member is a user defined class?
我在头文件中定义了一个类:
class TempLogger {
private:
int pin;
OneWire thermo;
public:
TempLogger(int);
float read();
};
和一个cpp文件:
TempLogger::TempLogger(int x) {
pin = x;
OneWire thermo(pin);
}
我的编译器声明"没有匹配函数调用'OneWire::OneWire()'指向CPP文件的第一行。我做错了什么,为什么?
看起来OneWire
没有非参数构造函数,它试图在TempLogger
初始化步骤调用。你既可以编写一个非参数构造函数,也可以在初始化列表中调用参数构造函数:
TempLogger::TempLogger(int x):pin(x),thermo(x){}
在您的代码中,您声明了另一个变量thermo
,从而隐藏了您的类成员变量
有一件事你肯定做错了,那就是构造函数
TempLogger::TempLogger(int x) {
pin = x;
OneWire thermo(pin); //This creates a local object inside the constructor which gets deleted directly after this statement
}
你可能想这样做:-
class TempLogger {
private:
int pin;
OneWire *thermo;
public:
TempLogger(int);
float read();
};
TempLogger::TempLogger(int x) {
pin = x;
thermo = new OneWire(pin);
}
相关文章:
- 如何确保C++函数在定义之前声明(如override关键字)
- 为什么在定义函数之前先声明它
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- Visual Studio中的函数声明和函数定义问题
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 如何在标头中声明(或定义)函数的问题
- 程序顶部的声明与定义(最佳实践)
- 类的前向声明之后的类成员函数定义,在类声明之前
- 静态变量声明和定义
- C++ G++ 编译器 - 错误:隐式声明的定义
- C++:错误重定义和先前声明
- 类模板静态数据成员定义/声明/初始化
- 只有一个定义/声明时标头声明变量的多堆定义错误
- OpenCV - Ptr 语法和类定义/声明 - 混淆?
- 如何为非类型模板类的专用化定义声明之外的方法
- 我如何防止静态类成员变量需要两个定义/声明
- 默认定义声明的详细程度不完整
- C++:非成员函数的定义/声明的位置
- 将比较操作符的重载定义/声明为库中的非成员函数
- C++头重新定义/声明混合