c++ - C++如何制作这种构造函数的原型?
问题描述
老实说,我什至不确定如何在谷歌上搜索它,并且由于我的尝试未能这样做,你能告诉我如何编写构造函数的原型以便我可以这样使用它吗?
// MyClass.h
class Object;
class MyClass {
Object a;
Object b;
std::string c;
public:
MyClass(int, int, std::string&); // I do not know how to declare this properly
};
// so that I can write this:
MyClass::MyClass(int a, int b, std::string& c = "uninstantialised") : a(a), b(b) {
this->c = c;
}
// so that when I call the constructor like this:
Object a();
Object b();
MyClass mc(a, b);
// it doesn't produce an error when std::string argument is not specified.
谢谢!
解决方案
默认参数需要在声明中指定,而不是在实现中。此外,您应该按值而不是按引用获取字符串,并将其移动到MyClass::c
成员中:
public:
MyClass(int a, int b, std::string c = "uninstantialised");
// ...
MyClass::MyClass(int a, int b, std::string c)
: a(a), b(b), c(std::move(c))
{ }
按值取值和使用std::move()
不是必需的,但建议使用它,因为它可以更有效地避免在某些情况下复制字符串。
我建议将私有数据成员重命名为避免将相同名称用于其他内容的名称。这里,c
既是私有成员,也是构造函数参数。您应该为成员使用不同的东西。像a_
,b_
例如c_
。附加下划线是命名私有数据成员的一种流行方式。
推荐阅读
- airflow - 将“snowflake-connector-python”安装到 GCP Cloud Composer 时出错
- xcode - MacOS 应用程序屏幕尺寸
- swift - 如何创建不可变的惰性属性?
- cmd - 如何终止批处理文件
- python - 即使 foreign_keys 为 ON,FOREIGN KEY 约束也会失败
- javascript - 是否可以使用带有 Javascript 的 HTML 的 CANVAS 上下文(ctx)来制作字体选择器?
- android - Admob 广告停止工作 - iOS14 是否也影响 android 版本控制?
- kotlin - 在接口方法中获取当前事务句柄
- c - * 之间有什么区别
和 * 在 C 中? - mysql - mysql 日志文件的文件位置