C++ 命名约定
C++有一系列的规则用于命名变量、函数和其他标识符。这些规则被称为命名约定,有助于使你的代码更易读和易维护。
在C++中命名约定的指导原则
变量名应该具有描述性和意义。例如,一个保存班级学生人数的变量名可以是”numStudents”或”studentCount”。
变量名应该使用小写字母,单词之间用下划线分隔。例如,”student_count”或”total_income”。
函数名应该使用驼峰命名法,每个单词的首字母大写,除了第一个单词。例如,”calculateTotalIncome”或”getStudentCount”。
常量应该以大写字母命名,单词之间用下划线分隔。例如,”PI”或”MAX_STUDENT_COUNT”。
类名应该使用驼峰命名法,每个单词的首字母大写,除了第一个单词。例如,”Student”或”CourseEnrollment”。
避免使用对其他程序员可能不熟悉的缩写或首字母缩写。
避免使用保留字或关键字作为变量或函数名。
C++代码(命名约定)
#include
// PascalCase is often used for function names
void PrintGreeting() {
std::cout << "Hello, world!" << std::endl;
}
int main() {
// camelCase is often used for variable names
int numberOfApples = 5;
int numberOfOranges = 3;
int totalFruit = numberOfApples + numberOfOranges;
// Some people use prefixes or suffixes to indicate the type of a variable
// (such as "str" for strings or "arr" for arrays)
std::string strCustomerName = "John Smith";
int arrScores[10] = {0};
// Other people use ALL_CAPS for constants
const int MAX_CUSTOMERS = 100;
// Some people use underscores to separate words in variable names
int num_customers = 10;
double avg_sale_amount = 25.50;
std::string customer_name = "John Smith";
// Finally, some people use Hungarian notation, where the type of a variable
// is indicated by the first few letters of its name (such as "i" for int,
// "d" for double, or "str" for string)
int iCount = 0;
double dTotal = 0.0;
std::string strName = "";
std::cout << "We have " << totalFruit << " pieces of fruit." << std::endl;
std::cout << "Number of customers: " << num_customers << std::endl;
std::cout << "Average sale amount: " << avg_sale_amount << std::endl;
std::cout << "Customer name: " << customer_name << std::endl;
return 0;
}
输出:
We have 8 pieces of fruit.
Number of customers: 10
Average sale amount: 25.5
Customer name: John Smith
命名约定的优势
以下是在C++中使用一致的命名约定的优势的一些示例:
提高可读性 :使用一致的命名约定可以通过查看名称来更容易理解变量或函数的目的。例如,如果你始终使用驼峰式命名法来命名变量,并使用帕斯卡命名法来命名函数,那么一眼就能看出哪些是变量,哪些是函数。
C++代码:
#include
int main() {
// Using a consistent naming convention (camelCase for variables) makes it
// easier to understand the purpose of each variable.
int numberOfApples = 5;
int numberOfOranges = 3;
int totalFruit = numberOfApples + numberOfOranges;
std::cout << "We have " << totalFruit << " pieces of fruit." << std::endl;
return 0;
}
输出:
We have 8 pieces of fruit.
增强可维护性 :一致的命名约定可以帮助您更轻松地在代码中找到特定的变量或函数。例如,假设您始终为存储特定类型数据的变量使用特定的前缀或后缀(例如用于字符串的”str”或数组的”arr”)。那么,在您需要进行更改时,就可以更轻松地找到所有该类型的变量。
C++代码
#include
// Using a consistent naming convention (PascalCase for functions) makes it
// easier to locate specific functions in your code.
void PrintGreeting() {
std::cout << "Hello, world!" << std::endl;
}
int main() {
PrintGreeting();
return 0;
}
输出:
Hello, world!
减少错误: 使用一致的命名约定可以帮助减少代码中的错误,因为它可以更容易地识别出具有相似名称但用途不同的变量或函数。例如,假设您一贯使用特定的前缀或后缀来命名存储某些类型数据的变量(如用于字符串的”str”或用于数组的”arr”)。在这种情况下,在特定上下文中使用错误类型的变量时,将更容易发现由此引起的错误。
C++ 代码
#include
int main() {
// Using a consistent naming convention (prefixes to indicate variable type)
// can help reduce errors by making it easier to identify the correct type
// of variable to use in a given context.
int numCustomers = 10;
double avgSaleAmount = 25.50;
std::string customerName = "John Smith";
std::cout << "Number of customers: " << numCustomers << std::endl;
std::cout << "Average sale amount: " << avgSaleAmount << std::endl;
std::cout << "Customer name: " << customerName << std::endl;
return 0;
}
输出:
Number of customers: 10
Average sale amount: 25.5
Customer name: John Smith
增加合作: 一个一致的命名约定可以使多个人在同一个代码库上工作更容易,因为它可以确保每个人都使用相同的命名约定。这有助于避免混淆和减少在合并代码更改时发生冲突的风险。
C++ 代码
#include
// Using a consistent naming convention (PascalCase for functions) can help
// ensure that multiple people working on the same codebase are using the same
// conventions, which can reduce conflicts and confusion when merging code
// changes.
void PrintGreeting() {
std::cout << "Hello, world!" << std::endl;
}
int main() {
PrintGreeting();
return 0;
}
输出:
Hello, world!
提升专业能力 : 遵循一致的命名约定可以展示专业精神和注重细节,特别是在与客户合作或在专业环境中工作时更加重要。使用一致的命名约定还可以使您的代码更具视觉吸引力和易读性,这在任何情况下都是宝贵的资产。
C++ 代码
#include
int main() {
// Using a consistent naming convention (camelCase for variables) can make
// your code more visually appealing and easier to read, which can be a
// valuable asset in any situation.
int numberOfApples = 5;
int numberOfOranges = 3;
int totalFruit = numberOfApples + numberOfOranges;
std::cout << "We have " << totalFruit << " pieces of fruit." << std::endl;
return 0;
}
输出:
We have 8 pieces of fruit.
命名规范的缺点
额外努力 : 遵守一致的命名规范需要额外的努力和纪律,因为您每次命名变量或函数时都必须记住使用正确的规范。如果您与有不同命名约定的团队合作,或者您在一个要求您遵循与您习惯不同的特定命名约定的项目上工作,则这可能特别具有挑战性。 C ++代码
#include
int main() {
// Adhering to a consistent naming convention (camelCase for variables)
// requires extra effort and discipline, as you have to remember to use the
// correct conventions every time you name a variable or function.
int numberOfApples = 5;
int numberOfOranges = 3;
int totalFruit = numberOfApples + numberOfOranges;
std::cout << "We have " << totalFruit << " pieces of fruit." << std::endl;
return 0;
}
输出:
We have 8 pieces of fruit.
限制: 使用一致的命名约定也可能具有限制性,因为它可能限制你在变量或函数命名上的选择。例如,如果你使用的命名约定要求你为某些类型的变量使用特定的前缀或后缀,你可能无法使用某些你本来更喜欢的名字。
C++代码
#include
int main() {
// Using a consistent naming convention (prefixes to indicate variable type)
// can be limiting, as it may restrict the names you can use for variables.
// For example, if you want to use a name like "customer_name" for a string
// variable, you may not be able to do so if your naming convention requires
// you to use a specific prefix or suffix (such as "str" or "s").
std::string strCustomerName = "John Smith";
std::cout << "Customer name: " << strCustomerName << std::endl;
return 0;
}
输出:
Customer name: John Smith
冲突的可能性: 当涉及到命名约定时,不同的人或团队可能有不同的偏好,如果每个人都不在同一页面上,这可能会导致冲突。如果您正在进行一个有许多贡献者的大型项目,这可能特别成问题。
C++代码
#include
int main() {
// Different people or teams may have different preferences when it comes to
// naming conventions, which can lead to conflicts if everyone is not on the
// same page.
int numberOfApples = 5;
int numberOfOranges = 3;
int totalFruit = numberOfApples + numberOfOranges;
std::cout << "We have " << totalFruit << " pieces of fruit." << std::endl;
return 0;
}
输出:
We have 8 pieces of fruit.
灵活性不足: 根据您使用的命名约定,可能并不总是最合适或直观的选择。例如,如果您使用的约定要求您在变量中使用camelCase,那么您可能不得不为变量想出不太直观的名称,而这些变量在使用下划线或其他分隔符时更自然。
C++ 代码
#include
int main() {
// Depending on the naming convention you are using, it may not always be the
// most appropriate or intuitive choice for every situation. For example, if
// you are using a convention that requires you to use camelCase for variables,
// you may have to come up with less intuitive names for variables that would
// be more naturally expressed using underscores or other separators.
int num_customers = 10;
double avg_sale_amount = 25.50;
std::string customer_name = "John Smith";
std::cout << "Number of customers: " << num_customers << std::endl;
std::cout << "Average sale amount: " << avg_sale_amount << std::endl;
std::cout << "Customer name: " << customer_name << std::endl;
return 0;
}
输出:
Number of customers:
C++,Python,Java和C都是具有各自变量和函数命名规则的编程语言。以下是这些语言所遵循的命名约定之间的主要区别:
C++:在C++中,变量和函数通常使用camelCase命名,每个单词的首字母大写,除了第一个单词(例如“numberOfApples”)。常量变量经常使用ALL_CAPS命名,单词之间用下划线分隔(例如“MAX_CUSTOMERS”)。
示例
#include
// camelCase is often used for variable names
int numberOfApples = 5;
int numberOfOranges = 3;
int totalFruit = numberOfApples + numberOfOranges;
// ALL_CAPS is often used for constant variables
const int MAX_CUSTOMERS = 100;
int main() {
std::cout << "We have " << totalFruit << " pieces of fruit." << std::endl;
std::cout << "MAX_CUSTOMERS is " << MAX_CUSTOMERS << "." << std::endl;
return 0;
}
输出结果:
We have 8 pieces of fruit.
MAX_CUSTOMERS is 100.
# Snake case variable
number_of_apples = 10
# Snake case function
def calculate_sum(a, b):
return a + b
# ALL CAPS constant
variable MAX_CUSTOMERS = 100
# 蛇形命名法的变量
number_of_apples = 10
# 蛇形命名法的函数
def calculate_sum(a, b):
return a + b
# 全大写的常量变量
MAX_CUSTOMERS = 100
# snake_case is often used for variable names
number_of_apples = 5
number_of_oranges = 3
total_fruit = number_of_apples + number_of_oranges
# ALL_CAPS is often used for constant variables
MAX_CUSTOMERS = 100
print(f"We have {total_fruit} pieces of fruit.")
print(f"MAX_CUSTOMERS is {MAX_CUSTOMERS}.")
输出:
We have 8 pieces of fruit.
MAX_CUSTOMERS is 100.
Java: 在Java中,变量和函数通常使用驼峰命名法命名,其中每个单词的第一个字母大写,除了第一个单词(例如,”numberOfApples”)。常量变量通常使用全大写命名,单词之间用下划线分隔(例如,”MAX_CUSTOMERS”)。
在C中,变量和函数通常使用蛇形命名法命名,单词之间用下划线分隔(例如,”number_of_apples”)。 常量变量通常使用全大写命名,单词之间用下划线分隔(例如,”MAX_CUSTOMERS”)。 需要注意的是,这些只是一般约定,可以在这些语言中使用不同的命名约定。 然而,一般来说,遵循你所工作语言或社区遵循的约定是一个好主意,因为这样可以让其他人更容易阅读和理解你的代码。
示例
public class Main {
// camelCase is often used for variable names
int numberOfApples = 5;
int numberOfOranges = 3;
int totalFruit = numberOfApples + numberOfOranges;
// ALL_CAPS is often used for constant variables
static final int MAX_CUSTOMERS = 100;
public static void main(String[] args) {
System.out.println("We have " + totalFruit + " pieces of fruit.");
System.out.println("MAX_CUSTOMERS is " + MAX_CUSTOMERS + ".");
}
}
输出:
We have 8 pieces of fruit.
MAX_CUSTOMERS is 100.