当前位置: 代码迷 >> 综合 >> Effective C++读书笔记(五)——设计与声明
  详细解决方案

Effective C++读书笔记(五)——设计与声明

热度:24   发布时间:2024-02-24 16:19:06.0

1.让接口容易被正确使用,不易被误用

class Date
{
public:Date(int month, int day, int year)...
};上述接口可能会引起客户调用的错误,即填写顺序出错:
Date d(2, 30, 2020);
Date d(30, 2, 2020);进一步,可以将month,day,year封装成struct或classclass Date
{
public:Date(const Month& m, const Day& d,const Year& y)...
};这样调用的时候会直接报类型不匹配:
Date m_date(Month(12),Day(20),Year(2020));//正确
Date m_date1(Day(20),Month(12),Year(2020));//错误
//error: no matching function for call to ‘Date::Date(Day, Month, Year)’
但是构造函数内仍需要做Day、Month和Year之间的关系以及大小限制。

STL容器的接口十分一致,size函数对各个容器都适用,不像Java中数组适用length,Lists使用size。

2. 设计class犹如设计type

3.宁以pass-by-reference-to -const替换pass-by-value