贡献者: addis
operator= 等函数使用 default 或者 delete. 格式为 fun() = default 或 fun() = delete.
operator bool() {} 该函数的 return type 是 bool,将当前 class type 转换为 bool 类型。在前面加 explicit 可以阻止 implicit conversion,而只允许 explicit conversion。
operator=). 当 Derived Class 重新定义了 Base Class 的同格式函数时, 就把 Base Class 的函数覆盖了, 若要用 Base Class 的函数, 就在函数前面加 Base Class 名和 ::.
class CCandyBox : CBox {...}; 这种情况下默认 class CCandyBox : private CBox {...};
protected 和 private 对当前的 class 来说效果是一样的, 只是继承的时候有所不同.
operator=), 可以在 member 前面加 this->, 或者在 Derived Class 内部的一开始声明如 using BaseClass::m_data; 这样做仍然不能获取 Base Class 的 private members.
final 可以禁止被继承, 如 class CCandyBox final {...};
friend Cbox; class 声明只是一厢情愿的。friend 声明不会被继承。
virtual double volume() const override
final 可以防止 base class 函数被 override,如 virtual double volume() const final
virtual double volume() const = 0; 也可以不写 = 0,但是不定义该函数(前者更有保障一些)。含有 pure virtual function 的 class 叫做 抽象类(abstract class), 抽象类只能被继承, 不能创建 object, 但可以声明指针。
dynamic_cast<>() 可以将指针在 base class 和 derived class 间转换。注意 dynamic_cast<>() 只能对 polymorphic class 使用。
dynamic_cast<derived类>() 也可以判断一个 base 指针是否指向 derived类,如果否,返回 null pointer。
static_cast<CDerived&>() 得到 derived class。例如 NR3 工程中
template <class T, class T1, class T2>
void myplus(NRbase<T> &v, NRbase<T1> &v1, NRbase<T2> &v2)
{
// if v, v1, v2 are vectors
/*auto& v_ = static_cast<NRvector<T>&>(v);
auto& v1_ = static_cast<NRvector<T1>&>(v1);
auto& v2_ = static_cast<NRvector<T2>&>(v2);*/
// if v, v1, v2 are matrices
auto& v_ = static_cast<NRmatrix<T>&>(v);
auto& v1_ = static_cast<NRmatrix<T1>&>(v1);
auto& v2_ = static_cast<NRmatrix<T2>&>(v2);
// check v1 and v2 has the same size
v_.resize(v1_);
for (Long i = 0; i < v1.size(); ++i)
v(i) = v1(i) + v2(i);
}
typedef 和 using 同样由 private, protected 和 public 之分, 和 data member 是一样的.
operator= 不会被继承
operator= 自变量用 template, 那么默认的 operator= 会首先被使用! 这种情况下若不想用默认的, 那么就自己写一个默认的 operator=(rhs) 然后在函数体调用 template 版本即可: return operator=<T1>(rhs).
double x = double(), 生成的就是 0 或等效的值. 注意不能是 double x(), 这个什么都不会定义, 且不会报错.
a + b = c 对 complex<double> a, b, c 是合法的! 如果想禁止这么做, 函数返回 const 类型即可.
const T & 指向 temporary (例如 T()), 那么 temporary 的寿命会随 const T& 延长. 例如函数可以返回了指向 temporary 的 const T & 没有问题. 但这么做很危险, 因为如果 const T& 再次作为自变量传递到另一个函数中(或者再次被返回?) temporary 就会失效.
1. ^ 本文部分参考 Ivor Horton 的 C++ 教程
 
 
 
 
 
 
 
 
 
 
 
友情链接: 超理论坛 | ©小时科技 保留一切权利