C++ 代码优化:使用成员初始化列表
#include 'model.hpp'
class NotificationCenter { private: NotificationReceiverModel receiverModel;
public: NotificationCenter(NotificationReceiverModel receiver) : receiverModel(receiver) {} };
#ifndef NOTIFYME_MODEL_HPP #define NOTIFYME_MODEL_HPP
#include
struct NotificationReceiverModel { std::string userid; std::string username;
NotificationReceiverModel(std::string userid, std::string username) : userid(userid), username(username) {}
};
#endif //NOTIFYME_MODEL_HPP
这段代码有两个问题:
- 在 NotificationReceiverModel 的构造函数中,应该使用成员初始化列表来初始化成员变量,而不是使用赋值语句来初始化它们。应该修改为:
NotificationReceiverModel(std::string userid, std::string username)
: userid(userid), username(username) {}
- 在 NotificationCenter 的构造函数中,应该使用成员初始化列表来初始化 receiverModel 成员变量,而不是在函数体内赋值。应该修改为:
NotificationCenter(NotificationReceiverModel receiver)
: receiverModel(receiver) {}
原文地址: https://www.cveoy.top/t/topic/m0wE 著作权归作者所有。请勿转载和采集!