C++对象编程与分数数值表示的深入解析
1. C++构造函数与析构函数的优化
在C++编程中,若仅需默认构造函数来初始化数据成员,其实无需手动编写构造函数和析构函数。Bjarne Stroustrup和Herb Sutter建议:“不要定义仅用于初始化数据成员的默认构造函数,而是使用类内成员初始化器”,编译器会自动为我们“生成函数”,这样可能更高效。
以下是一个去除了构造函数和析构函数,使用类内成员初始化器的分数类示例:
// fraction.hpp
// Simple fraction class.
#ifndef FRACTION_HPP
#define FRACTION_HPP
// Uses the following C functions
extern "C" int writeStr(char *);
extern "C" int getInt(int *);
extern "C" int putInt(int);
class fraction
{
int num{0}; // numerator
int den{1}; // denominator
public:
void get(); // gets user's values
void display(); // displays fraction
void add(int theValue); // adds integer
};
#endif
超级会员免费看
订阅专栏 解锁全文
103

被折叠的 条评论
为什么被折叠?



