C++ 将现有对象传递给构造函数或构造新对象
对我来说,解释这一点最简单的方法是用一种我更熟悉的语言,C:C++ 将现有对象传递给构造函数或构造新对象,c++,arduino,C++,Arduino,对我来说,解释这一点最简单的方法是用一种我更熟悉的语言,C: public class ServerLib { private SoftwareSerial _bt; private string _name, _game; public ServerLib(int rx, int tx, string name, string game) { _bt = new SoftwareSerial(rx, tx); _bt.begin(960
public class ServerLib {
private SoftwareSerial _bt;
private string _name, _game;
public ServerLib(int rx, int tx, string name, string game) {
_bt = new SoftwareSerial(rx, tx);
_bt.begin(9600);
_name = name;
_game = game;
}
public ServerLib(ref SoftwareSerial bt, string name, string game) {
_bt = bt;
_name = name;
_game = game;
}
}
我试图在一个ARDUINO库中这样做,所以我假设C++,并尝试了以下的事情:
class ServerLib {
public:
ServerLib(int rx, int tx, String name, String game);
ServerLib(SoftwareSerial serial, String name, String game);
private:
SoftwareSerial _bt;
String _name;
String _game;
};
ServerLib::ServerLib(int rx, int tx, String name, String game) : _bt(rx, tx) {
_name = name;
_game = game;
_bt.begin(9600);
}
ServerLib::ServerLib(SoftwareSerial serial, String name, String game) : _bt(serial) {
_name = name;
_game = game;
}
这可以编译,但只有第一个构造函数可以工作,如果我使用第二个构造函数,那么使用SoftwareSerial的所有尝试似乎都无效。
如果我注释掉第一个构造函数并用
ServerLib::ServerLib(SoftwareSerial& serial, String name, String game) : _bt(serial) {}
将字段改为SoftwareSerial&_bt,那么这个构造函数就可以正常工作了,但是我无法用这两个构造函数编译它。如果我保持原样,我会得到错误:
error: invalid initialization of reference of type 'SoftwareSerial&' from expression of type 'int'
将第一个构造函数更改为
ServerLib::ServerLib(int rx, int tx, String name, String game) : _bt(SoftwareSerial(rx, tx)) {}
错误
error: invalid initialization of non-const reference of type 'SoftwareSerial&' from an rvalue of type 'SoftwareSerial'
我最后一次尝试是在第一个构造函数中移动初始化,如下所示:
ServerLib::ServerLib(int rx, int tx, String name, String game) {
_bt = SoftwareSerial(rx, tx);
_bt.begin(9600);
}
但这导致了
error: uninitialized reference member 'ServerLib::_bt' [-fpermissive]
<>在C中,你是通过引用串行传递,但是在C++中,这实际上是一个拷贝。所以你得到了一个全新的串行对象,它可能没有打开
我会将_bt设置为std::unique _ptr,使用_bt=std::make_unique创建它,并使用std::move像那样传递它,或者在其他地方需要时使用std::shared _ptr。您遇到的错误与您上载的代码不一致。你如何调用构造函数?为什么在你的真实代码中是引用?C++中的引用与C中的引用完全不同,它们只使用相同的单词来命名。我所发布的错误是在这些行上,我把构造函数称为ServLIB Server 10、11、名称、游戏;或ServerLib serverbt、名称、游戏;其中,串行bt10、11;是的,我也这么认为,我之所以尝试将其作为引用传递,是因为ServerLib对象窥视SoftwareSerial以查看它是否应该处理任何字节,如果没有,它会让实际代码处理缓冲区中的内容时保持不变。如果您使用智能指针,您可以返回一个常量引用或指向它的指针进行查看,在构造函数中使用std::move传递一个,或者在另一个构造函数中使用std::make_unique自己创建一个。