C ++样式约定:类声明中的参数名称 [英] C++ Style Convention: Parameter Names within Class Declaration

查看:153
本文介绍了C ++样式约定:类声明中的参数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个相当新的C ++程序员,我想听到类声明中参数和命名参数的参数。

I'm a fairly new C++ programmer and I would like to hear the arguments for and against naming parameters within the class declaration.

以下是一个示例:

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_*/

vs。

vs.

#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 )中命名变量是多余的。特别是因为你必须担心更新两个地方的名称,使它们匹配。另一方面,没有名字,通常只能通过查看声明来确定参数对应的变量,这通常是混乱的。


I cannot decide. On the one hand, I feel that it is redundant to name the variables in both the declaration (.h) and the definition (.cpp). Especially since you have to worry about updating the names in both places so that they match. On the other hand, without names, it can often be confusing to determine what variables the parameters correspond to just by looking at the declaration.

那么,你的想法是什么?

So, what are your thoughts?

推荐答案

在声明中使用参数名称并使用好的参数名称会更好。这样,它们作为功能文档。否则,您将必须在标题中写入其他注释,并且使用好的参数/变量名称总是比使用注释更好。

It is much better to use the parameter names in the declaration, and use good parameter names. This way, they serve as function documentation. Otherwise, you will have to write additional comments in your header, and it is always better to use good parameter/variable names than to use comments.

异常:必须有一个特定的签名为外部原因,但参数没有实际使用。在这种情况下,您不应在实现中为它们命名。

Exception: when a function must have a certain signature for external reasons, but the parameters are not actually used. In this case, you should not name them in the implementation either.

这篇关于C ++样式约定:类声明中的参数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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