我是一个相当新的C++程序员,我希望听到在类声明中针对和反对命名参数的参数。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)中命名变量是多余的。特别是因为你必须担心在两个地方更新名称,以便它们匹配。另一方面,没有名称,通过查看声明来确定参数对应的变量通常会令人困惑。
那么,你有什么想法?
只是使用`int`和`double`,而不是`unsigned int`和`float`。在`unsigned int`的情况下,你可能试图记录一个值约束,但不是C++强制执行,它提供了许多陷阱,即没有收益,但是有很多不必要的痛苦。通常只使用无符号类型来处理位级别,或者在库函数中强制使用。在`float'的情况下,你可能试图节省内存。这是错误的,除非你有数十亿的学生。 :-)干杯&hth。 – 2010-10-15 18:36:47
@Alf P. Steinbach:哪些陷阱?为什么浮动足够时加倍?阐述。 – 2011-02-11 14:32:40