2009-11-25

本文介绍了C++中关于类的静态成员变量初始化、容器高效使用及拷贝控制成员之间的关系等技巧。特别强调了const静态成员变量可以在类体中初始化,并可用作数组维度;容器的高效使用建议先声明空容器后填充;以及如果类需要析构函数,则通常也需要拷贝构造函数和赋值操作符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1、静态成员变量为const int 型时,可以直接在类体中初始化
   这个功能可以用在定义一个数组
   Integral const static Members Are Special
   Ordinarily, class static members, like ordinary data members, cannot be initialized
   in the class body. Instead, static data members are normally initialized when they
   are defined.

   One exception to this rule is that a const static data member of integral type can be
   initialized within the class body as long as the initializer is a constant expression:

     class Account {
     public:
         static double rate() { return interestRate; }
         static void rate(double);  // sets a new rate
     private:
         static const int period = 30; // interest posted every 30 days
         double daily_tbl[period]; // ok: period is constant expression
     };
  A const static data member of integral type initialized with a constant value is a
  constant expression. As such, it can be used where a constant expression is required,
  such as to specify the dimension for the array member daily_tbl.

2、使用容器时,先声明一个空容器,以后当需要时再往里面插入值效率更高(省了拷贝构造函数一步)
   As a general rule (Section 9.1.1, p. 307), unless you intend to use the default initial
   value of the container elements, it is more efficient to allocate an empty container and
   add elements as the values for those elements become known
3、拷贝、赋值、析构函数关系
   A useful rule of thumb is that if a class needs a destructor, it will also need the
   assignment operator and a copy constructor. This rule is often referred to as the Rule
   of Three, indicating that if you need a destructor, then you need all three copy-control members.
4、类中数据成员初始化顺序是按照它们在类中声明顺序,析构时则相反

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值