explicit构造函数
explicit构造函数禁止了隐式的类型转换,防止由于隐式类型转换而造成的问题。
不允许被重载的运算符
不能重载的运算符只有5个:
. (成员访问运算符)
.* (成员指针访问运算符)
:: (域运算符)
sizeof (长度运算符)
?: (条件运算符)
几个特殊运算符重载的示例
/**
* 运算符重载
*/
#include <bits/stdc++.h>
using namespace std;
class Counter
{
private:
/* data */
int counter;
public:
Counter(/* args */);
~Counter();
operator int() { return counter; }
Counter &operator++()
{
counter++;
return *this;
};
Counter operator++(int)
{
Counter tmp = *this;
counter++;
return tmp;
};
Counter &operator--()
{
this->counter--;
return *this;
};
Counter operator--(int)
{
Counter pre(*this);
counter--;
return pre;
};
friend istream &operator>>(istream &is, Counter &obj)
{
is >> obj.counter;
//允许级联调用
return is;
};
friend ostream &operator<<(ostream &os, Counter &obj)
{
os<<obj.counter;
//允许级联调用
return os;
};
};
Counter::Counter(/* args */)
{
this->counter = 0;
}
Counter::~Counter()
{
}
int main()
{
Counter c;
cout << c<< endl;
cout << c++ << endl;
cout << c<< endl;
cout << ++c << endl;
cout << "--------------------" << endl;
cout << --c << endl;
cout << c-- << endl;
cout << c;
}
多继承中,构造函数与析构函数的调用顺序问题
/**
* 构造函数调用顺序问题
*/
#include<bits/stdc++.h>
using namespace std;
class base
{
private:
/* data */
public:
base(/* args */);
~base();
};
base::base(/* args */)
{
cout<<"base class constructor called"<<endl;
}
base::~base()
{
cout<<"base class destructor called"<<endl;
}
class mid_a:public base
{
private:
/* data */
public:
mid_a(/* args */);
~mid_a();
};
mid_a::mid_a(/* args */)
{
cout<<"class mid_a constructor called"<<endl;
}
mid_a::~mid_a()
{
cout<<"class mid_a destructor called"<<endl;
}
class mid_b:public base
{
private:
/* data */
public:
mid_b(/* args */);
~mid_b();
};
mid_b::mid_b(/* args */)
{
cout<<"class mid_b constructor called"<<endl;
}
mid_b::~mid_b()
{
cout<<"class mid_b destructor called"<<endl;
}
class C: public mid_a, mid_b
{
private:
/* data */
public:
C(/* args */);
~C();
};
C::C(/* args */)
{
cout<<"class C constructor called"<<endl;
}
C::~C()
{
cout<<"class C destructor called"<<endl;
}
int main()
{
C aaa;
}
输出:
base class constructor called
class mid_a constructor called
base class constructor called
class mid_b constructor called
class C constructor called
class C destructor called
class mid_b destructor called
base class destructor called
class mid_a destructor called
base class destructor called
分析:先尝试实例化mid_a,由于mid_a继承自base,因此调用了base的构造函数,然后调用mid_a的构造函数。然后对mid_b进行同样的操作。
结论:多继承的话,按照写的继承的顺序依次对父类进行实例化,然后每次调用的话都像一个栈一样,把它压进去。析构函数的调用顺序就是把这些对象从栈中弹出。