C++中的构造函数与析构函数不会在继承中被子类所继承,默认的构造函数(参数表为空)会自动调用,不管是否为显示调用,但是如果基类的构造函数带有参数时,需要进行显示调用,否则会进行报错。如:
- #include <iostream>
-
using namespace std;
-
-
class A
-
{
-
public:
-
A(int){cout<<"constructor A(int)"<<endl;}
-
};
-
class B:public A
-
{
-
public:
-
B(int i):A(i){cout<<"constructor B()"<<endl;}
-
};
-
-
int main()
-
{
-
B b(1);
-
return 0;
-
}
如果注释调显示调用构造函数A(i),则由于基类找不到合适的构造函数而进行报错。
在一般的类进行初始化时,顺序为:声明部分(调用默认空列表构造函数)-->类的构造函数
而赋值重载函数,复制构造函数也存在类似的道理,如果显示定义赋值重载函数,复制构造函数就需要进行显示调用,否则基类调用就会失败,但是如果没有定义赋值重载函数,复制构造函数,则就会默认调用基类的构造函数,这些性质在其他的重载函数中也存在。
- #include <iostream>
-
using namespace std;
-
-
class GameBoard
-
{
-
public:
-
GameBoard(){cout<<"GameBoard()\n";}
-
GameBoard(const GameBoard&){
-
-
cout<<"GameBoard(const GameBoard&)"<<endl;
-
}
-
GameBoard& operator=(const GameBoard&){
-
cout<<"GameBoard::operator=()"<<endl;
-
return *this;
-
}
-
~GameBoard(){cout<<"~GameBoard()"<<endl;}
-
};
-
-
class Game
-
{
-
GameBoard gb;
-
public:
-
Game(){cout<<"Game()"<<endl;}
-
Game(const Game& g):gb(g.gb){
-
cout<<"Game(const Game&)"<<endl;
-
}
-
Game(int){cout<<"Game(int)"<<endl;}
-
Game& operator=(const Game&g){
-
gb = g.gb;
-
cout<<"Game::operator=()"<<endl;
-
return *this;
-
}
-
class Other{};
-
//Automatic type conversion:
-
operator Other()const{
-
cout<<"Game::operator Other()"<<endl;
-
return Other();
-
}
-
~Game(){cout<<"~Game()"<<endl;}
-
};
-
class Chess:public Game{
-
GameBoard gb;
-
};
-
int main()
-
{
-
cout<<"Chess d1:"<<endl;
-
Chess d1;
-
cout<<"chess d2(d1)"<<endl;
-
Chess d2(d1);
-
cout<<" d1=d2 "<<endl;
-
d1 = d2;
-
cout<<"ending d1=d2"<<endl;
-
}
编译上面代码,运行如下:
- Chess d1:
-
GameBoard()
-
Game()
-
chess d2(d1)
-
//基类复制 函数默认被调用,因为基类中赋值函数显示调用
-
GameBoard(const GameBoard&)
-
Game(const Game&)
-
d1=d2
-
//默认赋值函数被调用,连内部成员函数的赋值函数也会被调用!!
-
GameBoard::operator=()
-
GameBoard::operator=()
-
Game::operator=()
-
ending d1=d2
如果显示定义了复制,赋值函数的话,这些默认函数就不会被调用了,如:
- class Chess:public Game{
-
GameBoard gb;
-
public:
-
Chess(){cout<<"chess constructor"<<endl;}
-
Chess(const Chess& c1){cout<<"chess copy-constructor"<<endl;}
-
Chess& operator=(const Chess&c){
-
cout<<"Chess operator=()"<<endl;
-
return *this;
-
}
编译运行如下:
- Chess d1:
-
GameBoard()
-
Game()
-
GameBoard()
-
chess constructor
-
chess d2(d1)
-
GameBoard()
-
Game()
-
GameBoard()
-
chess copy-constructor
-
d1=d2
-
Chess operator=()
-
//默认赋值函数没有被调用
-
ending d1=d2
因此在基类有默认赋值,复制函数时,在子类进行重写过程中必须进行显示调用。
另外,如果一个函数的行参为基类对象则子类对象也可以调用该函数,称之为
“upcast”,如:
- void f(Game g){
-
cout<<"f(Game g)"<<endl;
-
}
-
-
f(d1);
则结果如下:
阅读(3941) | 评论(0) | 转发(0) |