我是一个相当新的 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/