当成员是用户定义的类时,如何编写正确的类定义和声明?

How do I write a proper class definition & declaration when a member is a user defined class?

本文关键字:定义 声明 何编写 成员 用户      更新时间:2023-10-16

我在头文件中定义了一个类:

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);
}