The Element Style of C++

本文档详细介绍了C++编程中的通用原则、格式约定、命名约定及文档约定等内容,旨在帮助开发者编写清晰、一致且易于维护的代码。

 

 


Contents

0. Key Words

1. Introduction

2. General Principles

3. Fomatting Convetions

4. Naming Convetions

5. Documentation Convetions

 


Key Words

 

         characteristics; character; convention; effectiveness; capitalization; punctuation; exponential;

         indentation; typographic arrangement; no regard to;predictable; emphasize; inplementation;    

         anticipate;prefessionalism; foresight; deviation; implementation; wrap; truncate; delineate;  

         devoid; harizontally; abbreviation; generic; sufficient; adequately; excessively; vowel; consonant; ambiguity; reduce; differentiate; equivalent; perspective; enumerations;

         specification; self-explanatory; index; cross-reference; elegant; inspection; adjacent; intervening; synoptic; interfere; indicate; inapplicable; lifespan; assumption; allocate; workaround; publicize; isolate;

 

一.Introduction

 

        The positive reception to that book, coupled with recurring questions about C++ style issues,resulted in the edition for C++.

          This is deliberate, as many of the programming principles descried are timeless and valid across programming languages.

          The syntax of a programming language tells you what code it is possible to write——what machines will understand; Style tells you what you ought to write——what humans reading the code will understand.

 

.General Principles

        Simplicity

        Build simple classes and simple methods,Determine how much you need to do to meet the expectatios of your users.

        Clarity

        Ensure that each class,interface,method,variable and object has a clear purpose. Explain where, when, why and how to use each.

        Completeness

        Provide the mininum functionality that any reasonable user would expect to find and use. Create complete documentation. document all features and functionality.

        Consistency

        Similar entities should look and behave the same; dissimilar entities should look and behave differently. Create and apply standards whenever possible.

        Robustness

        Provide predictable, documented behavior in response to errors and exceptions. Do not hide errors and do not force clients to detect erros.

 

三. Formatting Convetions

       Break long statements into mutiple lines.

        Use a single space to seperate the keywords, parentheses, and curly braces in condition statements.

        Use a single space on either side of binary operators, except for the "." or "->" operators.

        Use blank lines to seperate each logical section in a method implementation.  

        Use blank lines to seperate each function definition in a source file.              

 

.  Naming Convetions

       the function declaration / the function definition.

         4.1 Preprocessor Macro Names

                ---------Use UPPERCASE and Underscores  for Preprocessor Macro Names;

                ---------Use a unique prefix to Macro Names;  

         4.2 Type and Constant Names

                ---------Use "UpperCamelCase" for Classes, Constants, Structures, Enumerations and Typedefs;

                ---------Use Nouns to Name Compound Types;  

                ---------Pluralize the Names of Collections;

         4.3 Function Names

                ---------Use "LowerCamelCase" for Function Names;

                ---------Use Verbs to Name Functions;

                ---------Use "is", "get", "set" to Name Accessor and Mutator Functions;    

                ------------------Your classes should provide read access to Boolean members using functions that begin with the word "is".  

                ------------------Your classes should provide read access to other members using functions that begin with the word "get".

                ------------------Your classes should provide read access to indexed members using a "get" function that takes a size_t index argument.

                ------------------Your classes should provide writhe access to members using functions that begin with the word "set".

 

 

                ---------Use Nouns to Names Variables.

                ---------Pluralize variables that identify collections. 

                ---------Name All Function Parameters.

                ---------Use other for Parameter Names in Copy Constructors and Assignment Operators.

                ---------Give Function Parameter the Same Name as the Member Variables you Assigned Them to. 

         4.4 Variable and Parameter Names

                ---------Use "LowerCamelCase" for Variable and Function Parameter Names;

          4.5 General Principles

                ---------Use Meaningful Names;

                ---------Use Familiar Namas;

                ---------Avoid the Use of Digits within Names;

                ---------Avoid Excessively Long Names;

                ---------Join the Vowel Generations——Use Complete Words.

                ---------Use "LowerCamelCase" for Abbreviations.

                ---------Do Not Use Case to Differentiate Names.

           **If you find yourself removing vowels simply to shorten a long name, then you need to qusetion whether the original name is appropriate.

           **Instead of simply giving the entity a new name that conveys less meaning, first reconsider its design or purpose. A refactoring of the entity may produce new classes, interfaces, methods, or variables that are more focued and  can be more meaningful yet simpler names. 

.  Documentation Convetions

         5.1 Document the softwear interfaces for those who must use it.

         5.2 Document the implementation for those who must maintian it.

         5.3 Keep the Comments and Code Synthronized. 

         5.4 Embed  API Reference Documentaion in the souce code.  

         5.5 Generate  API Reference Documentaion directely from the souce code.  

         5.6 Document All Significate Software Elements.  

         5.7 Document Software Elements as Early as possible.  

         5.8 Use Block Comments to Discribe the Programming Interface.

         5.9 Use one-Line Comments to Explain Implementation Details. 

                ---------The Purpose of specific variable or expressions.

                ---------Any implementation-level design decisions.

                ---------The source material for complex algorithms.

                ---------Defect fixes or workarounds.

                ---------Code that may benefit from further optimization or elaboration.

                ---------Any Known Problems, limitations, and deficiencies.

         5.10 Use a single Consistent Format and Organization for All Documentation Comments.

         5.11 Provide a Summary Description of Every Declared Element. 

         5.12 Document the Interface Exposed by Every Function.

         5.13 Document Thread Synchronization Requirements.

         5.14 Provide Examples to Illustrate Common and Proper Usage.  

         5.15 Document Important Preconditions, Postconditions and Invariant Conditions. 

         5.16 Document Known Defects and Deficiencies.  

         5.17 Use Active Voice to Describe Actors and Passive Voice to Describe Actions.  

         5.18 Use "This" rather than "The" when Referring to Instances of the Current Class.  

         5.19 Explain Why the code dose What it dose. 

         5.20 Avoid the use of End-Line Comments.

 

         5.22 Add a "fall-through" Comment beween Two Case labels if no break statement seperates those lables.

         5.23 Use Keywords to Mark Pending work, Unresovled Issues, Defects, and Bug Fixes.  

          

已经博主授权,源码转载自 https://pan.quark.cn/s/a4b39357ea24 常见问题解答 网页打开速度慢或者打不开网页? 受到多种因素的影响,对于非会员用户我们无法提供最优质的服务。 如果您希望得到最棒的体验,请至大会员页面("右上角菜单 → 大会员")根据说明操作。 请注意:受制于国际网络的诸多不确定性,我们无法对任何服务的可靠性做出任何保证。 如果出现了网络连接相关的问题,我们建议您先等待一段时间,之后再重试。 如果您在重试后发现问题仍然存在,请联系我们,并说明网络问题持续的时间。 图片下载后无法找到? 打开"右上角菜单 → 更多 → 修改下载路径",在弹出的对话框中可以看到当前图片的保存路径。 此外,由于网络因素,在保存图片之后,等待屏幕下方出现"已保存到..."后,才能在本地找到图片。 如何更改图片保存的目录? 请参见"右上角菜单 → 更多 → 修改下载路径"。 翻页不方便? 在点进某个图片后,通过在图片上向左或向右滑动,即可翻页查看下一个作品。 如何保存原图/导出动图? 长按图片/动图,在弹出的菜单中选择保存/导出即可。 输入账号密码后出现"进行人机身份验证"? 此为pixiv登陆时的验证码,请按照要求点击方框或图片。 在pxvr中注册pixiv账号后,收到验证邮件,无法访问邮件中的验证链接? 请复制邮件中的链接,打开pxvr中的"右上角菜单 → 输入地址"进行访问。 能否自动将页面内容翻译为汉语? 很抱歉,pxvr暂不提供语言翻译服务。 图片下载类型是否可以选择? 能否批量下载/批量管理下载? 已支持批量下载多图作品中的所有原图:找到一个多图作品,进入详情页面后,点击图片进入多图浏览模式,长按任意一张图片即可看到批量下载选项。 关于上述其他功能,我们...
考虑局部遮阴的光伏PSO-MPPT控制模型(Simulink仿真实现)内容概要:本文介绍了基于Simulink仿真实现的考虑局部遮阴的光伏PSO-MPPT控制模型,旨在通过粒子群优化(PSO)算法解决光伏发电系统在局部阴影条件下最大功率点跟踪(MPPT)的效率问题。文档不仅提供了该模型的技术实现方法,还列举了大量相关的MATLAB/Simulink仿真资源,涵盖电力系统、智能优化算法、机器学习、路径规划、信号处理等多个科研方向,适用于复现高水平期刊论文和开展创新性研究。文中强调科研需逻辑缜密、善于借力,并提倡结合实际仿真与理论分析以提升研究深度。 适合人群:具备一定电力电子、自动控制或新能源背景,熟悉MATLAB/Simulink环境,从事光伏系统优化、智能算法应用或相关领域研究的研发人员及硕博研究生。 使用场景及目标:①研究局部遮阴下光伏系统MPPT控制策略的性能提升;②利用PSO等智能优化算法解决非线性、多峰值优化问题;③复现SCI/EI级别论文中的MPPT控制模型;④开展光伏系统建模与仿真教学或项目开发。 阅读建议:建议读者结合文档提供的网盘资源,下载完整代码与模型文件,按照目录顺序逐步学习,重点理解PSO算法在MPPT中的应用机制,并通过修改参数、对比实验等方式深入掌握仿真细节,提升工程实践与科研创新能力。
1. What is an IDE (Integrated Development Environment), and what are its main components? 2. What is the role of a compiler in the C++ development process? 3. What is the difference between source code (e.g., a .cpp file) and an executable file? 4. In the "Hello, World!" program, what is the purpose of the line #include <iostream>? 5. What is special about the main() function in a C++ program? 6. Why do computers fundamentally operate using the binary (base-2) system? 7. What is the base of the hexadecimal system? Why is it often used by programmers as a shorthand for binary numbers? 8. Explain the "triad" method for converting an octal number to binary. 9. Briefly describe the "division by 2" method for converting a decimal number to binary. 10. What is the decimal value of the binary number 1011? 1. What is the purpose of the std::cout object? Which header file must be included to use it? 2.What is the difference between an escape sequence like \n and a manipulator like std::endl? (Hint: Both create a new line, but they have a subtle difference). 3.How would you print the following text to the console, including the quotes and the backslash: He said: "The file is in C:\Users\"? 4.Is it possible to write an entire multi-line text output using only one std::cout statement? If yes, how? 5.What is a syntax error? Give an example of a syntax error from Task 2. (Task 2: Debugging The following program contains several syntax errors. Copy the code into your IDE, identify the errors, fix them, and run the program to ensure it works correctly. Incorrect Code: */ Now you should not forget your glasses // #include <stream> int main { cout << "If this text" , cout >> " appears on your display, cout << " endl;" cout << 'you can pat yourself on ' << " the back!" << endl. return 0; "; ) Hint: Pay close attention to comments, header files, brackets ({}), operators (<<), semicolons, and how strings and manipulators are written.) 1. What is the difference between variable declaration and initialization? 2.What will be the result of the expression 7 / 2 in C++? Why? 3.What will be the result of the expression 10 % 3? What is the main purpose of the modulus operator? 4. What is the purpose of std::cin and the >> operator? 5. A beginner tries to swap two integer variables a and b with the code a = b; b = a;. Why will this not work correctly? 1. What is an algorithm? Name the primary ways to represent an algorithm. 2.List the main flowchart symbols and explain their purpose. 3.What are the three fundamental types of algorithm structures? Briefly describe each. 4.In a branching algorithm, what determines the flow of execution? 5.What is the key characteristic of a linear algorithm? 6.When is a cyclic algorithm structure used?7. 8. 9. 7.Explain the purpose of a connector in a flowchart. 8.What is the difference between a predefined process block and a standard process block? 9.In the context of solving a quadratic equation algorithm, what condition must be checked before calculating the roots? Why? 1. What are the three main approaches to data input and output offered by C++? 2. What is the purpose of the SetConsoleOutputCP(65001) and SetConsoleCP(65001)
functions in the provided C++ program example? 3. Explain the difference between the cin and cout objects in Stream 1/0. 4. When using formatted 1/0, which header file must be included to use manipulators like setw and setprecision? 5. List three manipulators used for data output in C++ and briefly describe what each one does. 6. In Formatted I/0 using printf), what are the conversion specifications for a decimal integer and a real number in exponential form? 7. What is the difference in how the & (address-of) operator is used when inputting a value for an integer variable versus a string variable using the scanf() function? 8. Which Character I/O function is used to output a single character to the screen, and which is used to output a string? 9. Describe the syntax and function of the ternary operator in C++. 10. What is the difference between the logical AND (&&) and logical OR (I|) operators when combining multiple conditions? 11. When is the default label executed in a C++ switch statement? 12. What is the primary purpose of the break statement within a switch block? 1. What is the main purpose of using loops in programming? 2. Explain the key difference between the for, while, and do while loops. 3. What happens if you forget to include the increment/decrement statement in a while loop? 4. How can you interrupt an infinite loop during program execution? 5. What is the role of the setw() and setfill) manipulators in C++? 6. In a nested loop, how does the inner loop behave relative to the outer loop? 7. What is type casting, and why is it used in loop calculations? 8. How does the do while loop differ from the while loop in terms of condition checking? 9. What output formatting options can be used to align numerical results in columns? 10*. How would you modify a loop to skip certain iterations based on a condition? 1. List the six main biwise operators in C++ and explain the function of each. 2. Why cannot bitwise operations be applied to variables of floating-point type? 3. Explain the purpose of the << (left shift) and >> (right shift) operators. What is the typical effect on the decimal value of a number when it is shifted left by 1? Shifted right by 1? 4. Describe the process of using a mask to check the value of a specific bit within an
integer. 5. How can you use the bitwise AND operator (&) to check if a number is even or odd?
Explain the logic. 6. What is the difference between the logical AND (&&) and the bitwise AND (&)? Provide an example scenario for each. 7. Explain the purpose of the ~ (bitwise NOT) operator. What is the result of applying it to a mask, and how can this be useful? 1. What is the primary goal of program debugging? What types of errors can it help identify? 2. Describe the difference between Step Over (F10) and Step Into (F11) debugging commands. When would you choose one over the other? 3. What is the purpose of a breakpoint in planned debugging? How do you set and remove a breakpoint in Visual Studio? 4. Explain the utility of the "Watch" window compared to the "Autos" or "Locals" windows during a debugging session. 5. What is the key difference between the Debug and Release configurations when building a project? Why is it necessary to create a Release version after successful debugging? 6. List at least three types of files commonly found in a project's Debug folder and briefly state their purpose (e.g., *.pdb). 7. During debugging, you notice a variable has an incorrect value. How can you change its value during runtime to test a hypothesis without modifying the source code? 8. What command is used to exit the debug mode and stop the current debugging session? 1. What is an array in C++? List its three main characteristics. 2. How are array elements numbered in C++? What is the valid index range for an array declared as int data[25];? 3. Explain the difference between array declaration and initialization. Provide an example of each. 4. What is an initializer list? What happens if the initializer list is shorter than the array size? 5. How can you let the compiler automatically determine the size of an array during initialization? 6. What values do elements of a local array contain if it is declared but not explicitly initialized? How does this differ from a global array? 7. What is an array out-of-bounds error? Why is it dangerous, and what are its potential consequences? 8. How do you calculate the number of elements in an array using the sizeof operator?
Provide the formula. What is a significant limitation of this method? 9. Why is it impossible to copy the contents of one array into another using the assignment
operator (arrayB = arrayA;)? What is the correct way to perform this operation? 10. Why does comparing two arrays using the equality operator (arrayA == arrayB) not check if their elements are equal? How should array comparison be done correctly? 11. What does the name of an array represent in terms of memory? 1. What is a pointer in C++ and what are its two main attributes? 2. Explain the difference between the & and * operators when working with pointers. 3. Why is pointer initialization critical and what dangers do uninitialized pointers pose? 4. What is the fundamental relationship between arrays and pointers in C++? 5. How does pointer arithmetic work and why does ptr + 1 advance by the size of the pointed type rather than 1 byte? 6. What is the difference between an array name and a pointer variable? Why can't you increment an array name? 7. What are the differences between const int*, int* const, and const int* const? 8. How can you safely iterate through an array using pointers, and what are the boundary risks? 9. What is a null pointer and why should you check for nullptr before dereferencing? 10. How do you access array elements using pointer syntax, and how does the compiler translate arr[i] internally? 1. What is a multidimensional array? How is a two-dimensional array structured in memory? 2. Explain the concept of an "array of arrays". How does this relate to the declaration int arr/ROWS//COLS;? 3. The name of a two-dimensional array without indices is a pointer constant. What does this pointer point to? What do the expressions *(A + i) and *(*(A + i) +j) mean for a two-dimensional array A? 4. Describe the different ways to access the element A/1/[2/ of a two-dimensional array
using pointers. 5. What is the rule for omitting the size of dimensions when initializing and when passing a multidimensional array to a function? Why is it allowed to omit only the first dimension? 6. Explain the principle of "row-major order" for storing two-dimensional arrays in memory.
How does this affect element access? 7. Why are nested loops the standard tool for processing multidimensional arrays?
Describe the typical pattern for iterating through a matrix. 1. How is a character string stored in memory in C++? What is the role of the null terminator (10), and why is it critical for C-style strings? 2. Why must the size of a char array declared to hold a string be at least one greater than the number of characters you intend to store? 3. The array name without an index is a pointer constant. What does the name of a char array point to? 4. What are the two main ways to initialize a C-style string? What is a common mistake when using the initializer list method, and what is its consequence? 5. Why is it necessary to add _CRT_SECURE_NO_WARNINGS to the preprocessor definitions in Visual Studio when working with many standard C library functions?
What is the alternative approach? 6. What is the key difference between stropy and strncpy? Why might strncpy be considered safer? 7. How does the stremp function determine if one string is "less than" another? Why can't you use the == operator to compare two C-style strings for content equality? 8. Describe the purpose and parameters of the strok function. How do you get all tokens from a string? 9. What do the functions strchr and strrchr do? How do they differ? 10. Explain what the strstr function returns and what it is commonly used for. 11. What is the purpose of the functions in the < cctype> header? Give three examples of such functions and their use. 12. What is the difference between tolower(c) and_tolower(c)? When should you use each? 1. What is a function in C++? Name the three core benefits of using functions in a program. 2. What is the difference between a function declaration (prototype) and a function definition? Provide examples. 3. What is a function signature? Which elements are part of the signature, and which are not? 4. What methods of passing parameters to a function do you know? Explain the difference between pass-by-value, pass-by-pointer, and pass-by-reference. 5. Why can't you pass an array to a function by value? What is the correct way to pass an array to a function? 6. What is variable scope? How is it related to functions? 7. How does a function return a value? What happens if a function with a non-void return type does not return a value on all control paths? 8. Can you use multiple return statements in a single function? Provide an example. 9. What is function overloading? What is it based on? 10. How is interaction between functions organized in a program? Provide an example program with several functions. 11. What are default parameters? How are they specified, and in what cases are they useful? 12. How can you prevent a function from modifying the data passed to it? What modifiers are used for this? 13. What is recursion? Provide an example of a recursive function. 14. What common errors occur when working with functions? How can they be avoided? 15. How do you use pointers to functions? Provide an example of declaring and calling a function through a pointer. 用中文解答
11-28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值