C++编程实践:利用const与inline替代#define

需积分: 0 5 下载量 147 浏览量 更新于2024-07-20 收藏 516KB PDF 举报
"Effective C++2e(中文).pdf" 在C++编程中,从C语言过渡到C++可能会带来一些挑战,因为C++扩展了C的特性,提供了更多的工具和概念。C++的复杂性在于它的灵活性和面向对象的特性,如私有和保护成员、函数重载、构造函数和析构函数、自定义操作符、内联函数、引用、友元、模板、异常处理以及名字空间等。这些特性让C++在解决问题时有了更多选择,但也使得适应新语言风格成为必要。 条款1:尽量用const和inline而不用#define 在C语言中,预处理宏#define常用于定义常量和简单的文本替换。然而,这种做法在C++中并不推荐,因为预处理宏有一些潜在的问题,如不参与类型检查、可能导致意外的副作用以及调试困难等。例如,使用#define定义的常量在错误信息中显示为原始值,而非定义的符号名,这给调试带来了困扰。 为了解决这些问题,C++引入了const关键字和inline函数。const用于定义常量,它不仅在编译时可见,而且参与类型检查,有助于防止类型错误。例如,定义一个浮点数常量ASPECT_RATIO可以写作: ```cpp const double ASPECT_RATIO = 1.653; ``` 这不仅解决了调试问题,还能确保常量在编译时就被解析。 对于定义全局函数或类成员函数,为了提高效率,可以使用inline关键字,告诉编译器尝试内联展开函数,避免函数调用的开销。但是,过度使用inline可能导致代码膨胀,因此需谨慎使用。 特殊情况下的const定义: 当定义指向常量的指针或常量指针时,const的位置至关重要。如果希望指针指向的数据不可变,应将const置于类型名之后: ```cpp const char* auth; // 指针指向的字符不可变,指针可变 ``` 若同时希望指针本身和其所指数据都不变,const则应置于指针前: ```cpp const char* const auth; // 指针和指针所指的字符都不可变 ``` 总结起来,从C转向C++时,应充分利用C++的新特性,如const和inline,以提高代码的可读性、安全性和效率,同时避免过度依赖预处理宏#define。这不仅是遵循良好的编程实践,也是提升C++代码质量的关键。通过逐步适应和掌握C++的这些核心概念,程序员可以更好地利用C++的强大功能,编写出更加高效和易于维护的代码。

优化代码 def cluster_format(self, start_time, end_time, save_on=True, data_clean=False, data_name=None): """ local format function is to format data from beihang. :param start_time: :param end_time: :return: """ # 户用簇级数据清洗 if data_clean: unused_index_col = [i for i in self.df.columns if 'Unnamed' in i] self.df.drop(columns=unused_index_col, inplace=True) self.df.drop_duplicates(inplace=True, ignore_index=True) self.df.reset_index(drop=True, inplace=True) dupli_header_lines = np.where(self.df['sendtime'] == 'sendtime')[0] self.df.drop(index=dupli_header_lines, inplace=True) self.df = self.df.apply(pd.to_numeric, errors='ignore') self.df['sendtime'] = pd.to_datetime(self.df['sendtime']) self.df.sort_values(by='sendtime', inplace=True, ignore_index=True) self.df.to_csv(data_name, index=False) # 调用基本格式化处理 self.df = super().format(start_time, end_time) module_number_register = np.unique(self.df['bat_module_num']) # if registered m_num is 0 and not changed, there is no module data if not np.any(module_number_register): logger.logger.warning("No module data!") sys.exit() if 'bat_module_voltage_00' in self.df.columns: volt_ref = 'bat_module_voltage_00' elif 'bat_module_voltage_01' in self.df.columns: volt_ref = 'bat_module_voltage_01' elif 'bat_module_voltage_02' in self.df.columns: volt_ref = 'bat_module_voltage_02' else: logger.logger.warning("No module data!") sys.exit() self.df.dropna(axis=0, subset=[volt_ref], inplace=True) self.df.reset_index(drop=True, inplace=True) self.headers = list(self.df.columns) # time duration of a cluster self.length = len(self.df) if self.length == 0: logger.logger.warning("After cluster data clean, no effective data!") raise ValueError("No effective data after cluster data clean.") self.cluster_stats(save_on) for m in range(self.mod_num): print(self.clusterid, self.mod_num) self.module_list.append(np.unique(self.df[f'bat_module_sn_{str(m).zfill(2)}'].dropna())[0])

2023-05-25 上传