C++ Style Convention:类声明中的参数名称

Sco*_*ott 5 c++ parameters coding-style 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_*/
Run Code Online (Sandbox Code Playgroud)

#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_*/
Run Code Online (Sandbox Code Playgroud)

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; }
Run Code Online (Sandbox Code Playgroud)

我做不了决定.一方面,我觉得在声明(.h)和定义(.cpp)中命名变量是多余的.特别是因为您不得不担心在两个地方更新名称以便它们匹配.另一方面,没有名称,通过查看声明来确定参数对应的变量通常会令人困惑.

所以你的想法是什么?

Gor*_*pik 19

在声明中使用参数名称要好得多,并使用好的参数名称.这样,它们就可以作为功能文档.否则,您将不得不在标题中写入其他注释,使用好的参数/变量名称总是比使用注释更好.

例外:当一个函数由于外部原因必须具有某个签名时,但实际上并未使用这些参数.在这种情况下,您不应该在实现中命名它们.

  • 例外:当参数明显或类型是自我记录时,例如,`Point3D(T,T,T)`和`Pair(Key,Value)`都非常清楚. (3认同)

Bin*_*ier 5

把名字放在两个地方,清晰是你在两个地方维护签名的任务所获得的奖励。