c++ - 这是模棱两可还是完全没问题?

标签 c++ constructor initialization standards coding-style

这段代码是模棱两可的还是完全没问题(通过标准批准/对现有的任何编译器都有一致的行为)?

struct SCustomData {
    int nCode;
    int nSum;
    int nIndex;
    SCustomData(int nCode, int nSum, int nIndex)
        : nCode(nCode)
        , nSum(nSum)
        , nIndex(nIndex)
    {}
};

编辑:
是的,我指的是成员变量与构造函数的形参同名。

最佳答案

不,在这种情况下没有歧义,但请考虑以下内容:

struct SCustomData {
//...
    void SetCode(int nCode)
    {
            //OOPS!!! Here we do nothing!
            //nCode = nCode;

            //This works but still error prone
            this->nCode = nCode;
    }
};

您应该注意一种现有的编码风格。例如General Naming Rule in Google C++ Coding Styles或阅读 Herb Sutter 和 Andrei Alexandrescu 的优秀著作“C++ Coding Standards: 101 Rules, Guidelines, and Best Practices”。

关于c++ - 这是模棱两可还是完全没问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2161397/

相关文章:

c++ - 打印数字的所有分区

c++ - 为什么我可以在 C++ 中调用已删除的私有(private)构造函数?

c++ - 构造函数中的静态变量,有什么缺点或副作用吗?

c++ - 如何在 C++ 对象中初始化数组

c++ - 在双向链表中搜索

c++ - SIGSEGV为什么不使过程崩溃?

c++ - 如何在文本文件中搜索单词,如果找到则打印出整行

c++ - 类成员可以用初始化列表中的另一个类成员来初始化吗?

c++ - 原始到用户定义的构造分配

arrays - VBA 数组 : "Testarray(10)" – What are the initial values of this *without* assigning *any* value to *any* cell?