C ++如何制作这种构造函数的原型?

时间:2019-06-01 18:03:48

标签: c++ c++11

老实说,我不确定该如何使用Google进行搜索,但是由于我的尝试失败了,您能告诉我如何编写构造函数的原型,以便以这种方式使用它吗?

// 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.

谢谢!

1 个答案:

答案 0 :(得分:3)

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