VS2022中C++类默认构造函数被删除错误的解决方法
修复C++默认构造函数被删除的错误
错误原因
你的User类包含引用类型成员DevicesList& devices,C++中引用必须在对象构造阶段就绑定到一个有效对象。编译器自动生成的默认构造函数无法完成这个引用的初始化操作,因此会被自动标记为删除状态,这就是User user1;这类代码报错的根本原因。
修复方案
方案1:将引用改为指针(灵活度高)
把引用成员替换为指针,指针可以在构造后再赋值,编译器就能正常生成默认构造函数:
修改类的私有成员:
private: unsigned int id; std::string username; unsigned int age; DevicesList* devices; // 替换为指针
更新init方法,添加设备列表的指针参数:
void init(unsigned int id, std::string username, unsigned int age, DevicesList* devList) { this->id = id; this->username = username; this->age = age; this->devices = devList; }
使用示例:
DevicesList user1Devices; User user1; user1.init(123456789, "blinkybill", 17, &user1Devices);
方案2:显式定义默认构造函数,绑定固定引用(适合共享场景)
如果所有User对象可以共享同一个DevicesList,可以先定义一个全局/生命周期足够长的设备列表,然后在默认构造函数中绑定引用:
// 全局或类外定义一个DevicesList实例 DevicesList sharedDeviceList; class User { private: unsigned int id; std::string username; unsigned int age; DevicesList& devices; public: // 显式默认构造函数,绑定到共享对象 User() : devices(sharedDeviceList) {} // 原有方法... void init(unsigned int id, std::string username, unsigned int age); // ... };
这种方式下,所有User对象都会使用同一个设备列表,仅适合特定业务场景。
方案3:用带参构造函数替代init方法(推荐,符合C++规范)
直接去掉init方法,编写带参数的构造函数,在对象创建时就完成所有成员(包括引用)的初始化,这是最符合C++ RAII原则的做法:
修改User类:
class User { private: unsigned int id; std::string username; unsigned int age; DevicesList& devices; public: // 带参构造函数,初始化所有成员 User(unsigned int id, std::string username, unsigned int age, DevicesList& devList) : id(id), username(username), age(age), devices(devList) {} // 原有方法... void clear(); unsigned int getID() const; std::string getUserName() const; unsigned int getAge() const; DevicesList& getDevices() const; void addDevice(Device newDevice); bool checkIfDevicesAreOn() const; };
使用示例:
DevicesList user1Devices; User user1(123456789, "blinkybill", 17, user1Devices); DevicesList user2Devices; User user2(987654321, "HatichEshMiGilShesh", 15, user2Devices);
内容的提问来源于stack exchange,提问作者AyAm
相关产品推荐
相关产品推荐

