C++ 风格约定 : Parameter Names within Class Declaration

标签 c++ coding-style parameters naming-conventions

我是一个相当新的 C++ 程序员,我想听听支持和反对在类声明中命名参数的争论。


这是一个例子:

Student.h

#ifndef STUDENT_H_
#define STUDENT_H_

#include <string>

using namespace std;

class Student
{
    private:
        string name;
        unsigned int age;
        float height, GPA;

    public:
        Student(string, unsigned int, float, float);

        void setAge(unsigned int);
};

#endif /*STUDENT_H_*/

对比

#ifndef STUDENT_H_
#define STUDENT_H_

#include <string>

class Student
{
    private:
        string name;
        unsigned int age;
        float height, GPA;

    public:
        Student(string name, unsigned int age, float height, float GPA);

        void setAge(unsigned int age);
};

#endif /*STUDENT_H_*/

Student.cpp

#include "Student.h"

Student::Student(   string name,
            unsigned int age,
            float height,
            float GPA) :

            name(name),
            age(age),
            height(height),
            GPA(GPA) {}

void Student::setAge(unsigned int age) { this -> age = age; }

我无法决定。一方面,我觉得在声明(.h)和定义(.cpp)中都命名变量是多余的。特别是因为您必须担心更新两个地方的名称以使它们匹配。另一方面,如果没有名称,仅通过查看声明就很难确定参数对应的变量。

那么,你有什么想法?

最佳答案

最好在声明中使用参数名称,并使用好的参数名称。这样,它们就充当功能文档。否则,您将不得不在标题中编写额外的注释,使用好的参数/变量名总是比使用注释更好。

异常(exception):当一个函数由于外部原因必须具有特定的签名,但实际上并没有使用参数时。在这种情况下,您也不应在实现中命名它们。

关于C++ 风格约定 : Parameter Names within Class Declaration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/771492/

相关文章:

c++ - 选择语句和隐式转换只给我字符串的第一个字符

c++ - 可变参数函数 va_arg() 返回不正确的参数

QtCreator : how to set parameters for debugging?

url - 使用SSI获取URL和参数

c++ - 保持 fstream 打开或每次需要使用时打开它哪个更有效?

python - 一般: always saving settings on close vs saving only when changed

c++ - 您可以将操纵器传递给函数吗?

c++ - 为什么这些 un​​icode 变量名称不能与 -fextended-identifiers 一起使用? «, » 和 ≠

c++ - 无向 DFS : how can I provide color maps as exterior properties?

javascript - Rails 内联 Javascript 和最佳实践