继承与组合
1、组合:新类中创建已存在类的对象,由此类中会包含已存在类对象,此种方式为组合。
在构造函数的调用的过程中要注意的是首先会调用基类的构造函数,然后调用子对象的构造函数,子对象构造函数的调用顺序是根据其定义的顺序而定的。为什么在构造函数中初始化子对象以及基类对象的对象你哦?这是C++的一个强化机制,确保在构造当前对象的时候就已经调用了基类的构造函数。
2、名字隐藏:任何时候重新定义了基类中的一个重载函数,在新类之中所有其他的版本则被自动地隐藏。这种方式与普通的重载不一样,只要返回类型的不同也会隐藏基类的函数。
/2013-8-1
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Base1
{
public:
int f (int a)const
{
return 1;
}
};
class Base
{
public:
virtual int f(int a) const
{
cout<<"Base::f()"<<endl;
return 1;
}
Base(){}
Base(const Base&base){}
};
class Drived1:public Base
{
public:
Drived1(){}
int f(int a,int b=2)const//用户自定义创建函数之后与基类的虚函数只是一个重载的函数,
{
return 2;
}
Drived1(const Drived1& d1){}
//void f(int a)const{}//定义的为非重载的形式,在为非虚基类中会发生重写,
};
void f(Base &base)//不是用引用会直接调用Base的拷贝构造函数。于是调用的还是基类的f。
{
cout<<&base<<endl;
base.f(2);//当用户对基类函数进行重载调用的依旧是基类的函数
}
int main()
{
string s("hello");
Base base;
cout<<"虚基类的大小为:"<<sizeof(base)<<endl;
Base1 base1;
cout<<"基类的大小为:"<<sizeof(base1)<<endl;
Drived1 d1;
int x=d1.f(5);
cout<<&d1<<endl;
f(d1);//作为基类并不知道在派生类中已经修改了的
x=d1.f(6);//在传递参数与f之后尽管Base接受Derived1的引用,但并不会改变原来的类型。
}
3、非自动继承的函数:operator=类似于构造函数的功能,因此是不能够被继承的。但是在继承过程中,若没有显示的创建,编译器会创建默认的构造函数和拷贝构造函数。
//modify by tj 2013-7-30
#include "stdafx.h"
#include <iostream>
using namespace std;
class GameBoard
{
void f(int){}
void f(char);
/*int main()
{
f();
}*/
int a;
public:
GameBoard()
{
cout<<"GameBoard()"<<endl;
}
GameBoard(const GameBoard& gameBoard)
{
a=gameBoard.a;
cout<<"GameBoard(const GameBoar&)"<<endl;
}
GameBoard& operator = (const GameBoard&)
{
cout<<"GameBoard::operator = ()"<<endl;
return *this;
}
~GameBoard()
{
cout<<"~GameBoard()"<<endl;
}
};
class Game
{
GameBoard mGb;
public:
Game()
{
cout<<"Game()"<<endl;
}
//Game(const Game& game)/*:mGb(game.mGb)*///会调用非拷贝的构造函数
//{
// cout<<"Game(const Game&)"<<endl;
//}
Game& operator = (const Game& g)
{
mGb=g.mGb;
cout<<"Game::operator=()"<<endl;
return *this;
}
Game(int)
{
cout<<"Game(int)"<<endl;
}
class Other {};
operator Other() const
{
cout<<"Game::operator Other()"<<endl;
return Other();
}
~Game()
{
cout<<"~Game()"<<endl;
}
};
class Chess:public Game{};
void f(Game::Other){};
class Checkers : public Game
{
public:
Checkers()
{
cout<<"Checkers()"<<endl;
}
//Checkers(const Checkers& c)/*:Game(c)*///若没有显示的定义拷贝构造函数将会调用的是构造函数
//{
// cout<<"Checkers(const Checkers& c)"<<endl;
//}
Checkers& operator = (const Checkers& c)
{
Game::operator =(c);
cout<<"Checkers::operator = ()"<<endl;
return* this;
}
};
int test3()
{
Chess d1;
Chess d2(d1);
d1=d2;
f(d1);
//Game::Other go;
//d1=go;
Checkers c1,c2(c1);//若没有显示的调用还会调用默认的构造函数
c1=c2;
return 1;
}
小结:1、若没有给派生类显示的定义拷贝构造函数调用的将会是构造函数。若构造函数没有显示的定义则会调用默认的构造函数。因为这两个函数都不会自动的继承。
4、如何选择组合与继承
利用组合的时候,新类不希望已存在的类作为其接口。新类应该作为嵌入类的私有对象。仅提供一些函数。若希望已存在的类中的每一个变量与成员都囊括,则应该使用的是继承。
5、向上类型转换
由继承类向基类进行类型转换。但是这个类接口可能会失去一些成员函数。
派生类中拷贝构造函数的调用顺序:基类的拷贝构造函数、各对象的拷贝构造函数。派生类是由基类派生的,在调用构造函数的时候会首先调用的是基类的构造函数,所以当使用向上类型转换的时候,派生类的引用就相当于基类的引用。但是随之的是会丢失一部分的函数,因为在基类中并不存在。