【问题标题】:Arduino passing in one object as a parameter in the constructor of another classArduino在另一个类的构造函数中传入一个对象作为参数
【发布时间】:2016-03-28 19:42:49
【问题描述】:

我对此很陌生,所以如果我叫错了名字,请原谅我。我想做的是将一个类的实例传递给另一个类的构造函数。我知道这些通常是在 .h 和 .cpp 文件中完成的,但是对于我正在运行的代码,它似乎并不在意,但是我可能是错的。除了类定义和构造函数之外,我已经取出了大部分代码。

我想在我的代码中包含一些现有的热敏电阻实例,例如coldtherm,并传递到Tempcontroller 的构造函数中,这样我就可以像在printfromthermistor 函数中显示的那样调用coldtherm。

//Thermistor Class
    class Thermistor
{

  int Thermpin;

public:
  Thermistor(int pin)
  {
  Thermpin = pin;
  }


double TEMPOutput()
  {
  return Thermpin;
  }  
void Update()
  {

  }
};

Thermistor coldtherm(1);

//Tempcontrol Class
class TempController
{

public:

TempController(Thermistor&) //Right here I want to pass in coldtherm to the Tempcontroller and be able to call functions from that class.


void printfromthermistor()
{

  Thermistor.TEMPOutput();
}


};

【问题讨论】:

    标签: c++ object arduino


    【解决方案1】:

    this 的重复。

    引用只能被初始化,不能被改变。像你展示的那样在构造函数中使用它意味着引用成员必须在构造函数中初始化

    class TempController
    {
      Thermistor & member;
    public:
      TempController( Thermistor & t ) { member = t; }; // assignment not allowed
      TempController( Thermistor & t ) : member(t) { }; // initialization allowed
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-09
      相关资源
      最近更新 更多