首页 > 解决方案 > 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.

谢谢!

标签: c++c++11

解决方案


默认参数需要在声明中指定,而不是在实现中。此外,您应该按值而不是按引用获取字符串,并将其移动到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_。附加下划线是命名私有数据成员的一种流行方式。


推荐阅读