【发布时间】:2009-04-21 07:46:06
【问题描述】:
我是一个相当新的 C++ 程序员,我想听听支持和反对在类声明中命名参数的论点。
这是一个例子:
学生.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)中都给变量命名是多余的。特别是因为您必须担心更新两个地方的名称以使它们匹配。另一方面,如果没有名称,仅通过查看声明来确定参数对应的变量通常会令人困惑。
那么,你的想法是什么?
【问题讨论】:
-
只使用
int和double,而不是unsigned int和float。在unsigned int的情况下,您可能正在尝试记录值约束,但不是 C++ 强制它提供了许多陷阱,即没有收益,但有很多不必要的痛苦。通常只在处理位级别或库函数强制使用的地方使用无符号类型。对于float,您可能正在尝试节省内存。除非你有数十亿学生,否则这是错误的。 :-) 干杯&hth。 -
@Alf P. Steinbach:有哪些陷阱?当浮点数足够时为什么要加倍?详细说明。
标签: c++ coding-style parameters naming-conventions