默认成员值最佳实践 [英] Default member values best practice

查看:110
本文介绍了默认成员值最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写C ++ 11代码以在类的头文件中为类成员设置默认值时是否是良好的做法?

Is it good practice when writing C++11 code to set default values for class members in the header file of the class?

这在类的构造函数中?

编辑:

我的意思是:

foo.h

#include <string>

using std::string;

class Foo{
    private:
        string greet = "hello";
    public:
        Foo();
};

VS

cpp (当然有必要的头文件,但没有类的初始化):

foo.cpp (of course with the necessary header file, but without the in-class initialization):

Foo::Foo(){
    greet = "hello";
}

哪一个更好,为什么?

推荐答案

如果类成员总是以相同的初始值初始化,那么你应该使初始化器内联,以避免重复。如果初始值依赖于构造函数,那么将其放在构造函数初始化器列表中。

If a class member is always initialized with the same initial value, then you should make the initializer inline, so as to avoid duplication. If the initial value depends on the constructor, then put it in the constructor initializer list. (And never use assignment in the way you did.)

示例:

class Foo
{
    bool done = false;   // always start like this
    int qty;
    Bar * p;

public:
    Foo()                        : qty(0),              p(nullptr)    { }
    Foo(int q, Bar * bp)         : qty(q),              p(bp)         { }
    explicit Foo(char const * s) : qty(std::strlen(s)), p(new Bar(s)) { }

    // ...
};

在这个假设的例子中,成员 done 始终需要以 false 开始,因此最好在内联中写入初始化程序。其他两个成员 qty p 可以在三个不同构造函数的每个中初始化不同,因此它们被初始化。

In this hypothetical example, the member done is always required to start as false, so it's best to write the initializer inline. The other two members, qty and p, can be initialized differently in each of three different constructors, so they are initialized inside the constructors' initializer lists.

一个curiosum:请注意,提供一个内联初始化器会阻止你的类有一个琐碎的默认构造函数

这篇关于默认成员值最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆