面向对象
- 抽象
- 封装
- 继承 代码复用,一种类层次的复用,复用不可能完完全全一样的拿过来复用,而最主要为了多态
派生类 : 基类
子类 : 父类
无法继承构造析构方法(子类无法决定父类的生亡)
构造一个子类对象: 先构造父类,再构造子类
继承都继承了私有成员只不过访问权限不同
-
- 公有继承
派生类可访问基类公有和保护成员
派生类的对象只能访问基类的公有成员
思考以下代码输出结果为什么是32?
//基类
class Base
{
public:
void print()
{
cout<<"Base::print()"<<endl;
}
public:
void SetA(int n)
{
a = n;
}
protected:
int b; //
private:
int a;
};
//派生类
class D : public Base
{
public:
void list()
{
cout<<"D::list()"<<endl;
x = 10;
//a = 100;
SetA(100); //派生类可访问基类公有成员
b = 10; //派生类可访问基类保护成员
}
protected:
void show()
{
cout<<"D::show()"<<endl;
}
private:
int x;
};
void main()
{
D d;
d.list();
d.print(); //派生类对象只能访问基类公有成员
d.SetA(10); //派生类对象只能访问基类公有成员
//d.b = 10; //派生类对象只能访问基类公有成员不能访问私有
}
-
- 保护继承
想象成基类公有成员全部变成了保护成员
- 保护继承
派生类可访问基类公有和保护成员
派生类对象只能访问派生类的公有成员且不能访问基类的任何成员
class Base
{
public:
void print()
{
cout<<"Base::print()"<<endl;
}
public:
void SetA(int n)
{
a = n;
}
protected:
int b; //
private:
int a;
};
class D : protected Base
{
public:
void list()
{
cout<<"D::list()"<<endl;
print();
b = 10;
//a = 100;
}
protected:
void show()
{
cout<<"D::show()"<<endl;
print();
}
private:
int x;
};
void main()
{
D d;
//d.print();
}
-
- 私有继承
派生类可访问基类公有和保护成员
派生类对象只能访问派生类的公有成员且不能访问基类的任何成员
思考以下代码输出结果为什么是32?
class Person
{
private:
string _name = "tony";
};
//继承
class Student : public Person
{
private:
int _stuid;
};
class Teacher : public Person
{
private:
int _jobid;
};
int main()
{
cout<<sizeof(Student)<<endl; //32
Student s;
return 0;
}
定义一个派生类对象时,基类和派生类的构造顺序是怎样的?
class Base
{
public:
Base()
{
cout << "Base::Base()" << endl;
}
~Base()
{
cout << "Base::~Base()" << endl;
}
public:
void print()
{
cout << "Base::print()" << endl;
}
private:
int a;
};
//
class D : public Base
{
public:
D()
{
cout << "D::D()" << endl;
}
~D()
{
cout << "D::~D()" << endl;
}
public:
void list()
{
cout << "D::list()" << endl;
print();
}
protected:
void show()
{
cout << "D::show()" << endl;
}
private:
int x;
};
void main()
{
D d;
}
以上程序的运行结果如下:
Base::Base()
D:😄()
D::~D()
Base::~Base()
由此可知派生类对象的构造会先构造基类再构造派生类,析构顺序正好相反
-
- 单继承
class Base
{
public:
void print()
{
cout<<"Base::print()"<<endl;
}
public:
void SetA(int n)
{
a = n;
}
protected:
int b; //
private:
int a;
};
class D : public Base //单继承
{
public:
void list()
{
cout<<"D::list()"<<endl;
print();
b = 10;
}
protected:
void show()
{
cout<<"D::show()"<<endl;
}
private:
int x;
};
-
- 多继承
class Base
{
public:
void print()
{
cout<<"Base::print()"<<endl;
}
public:
void SetA(int n)
{
a = n;
}
protected:
int b; //
private:
int a;
};
//
class D : public Base //单继承
{
public:
void list()
{
cout<<"D::list()"<<endl;
print();
b = 10;
}
protected:
void show()
{
cout<<"D::show()"<<endl;
}
private:
int x;
};
class E : public D, public Base //多继承
{
public:
void fun()
{
cout<<"E::fun()"<<endl;
list();
//print();
}
};
多态