1.派生类 -> 基类(自动转换)
引用/ 指针转换
对象转换 // 对象转换有问题
2.基类 -> 派生类
基类到派生类自动转换不存在
强制转换 Bulk_item *p = static_cast<Bulk_item *>(&item);
==================================================
3.友元与继承
友元可以访问类的private和protected成员
友元不能继承
#include <iostream>
using namespace std;
class Base
{
friend class Frnd;
friend class D2;
protected :
int i;
};
class D1 : public Base
{
friend class Frnd;
friend class D2;
private :
int j ;
};
class Frnd {
public:
int mem(Base b) {return b.i; }
int mem(D1 d) {return d.j; }
};
class D2 : public Frnd {
public:
int mem(Base b) {return b.i;}
int mem(D1 d) { return d.j;}
};
int main(void)
{
Base a;
D1 b;
Frnd c;
D2 d;
return 0;
}
==================================================
4 静态成员与继承
基类的static 成员在整个继承层次中只有一个实例
在派生类中访问static成员的方法
基类名::成员名
子类名::成员名
对象.成员名
指针->成员名
成员名
#include <iostream>
using namespace std;
class A
{
public :
static std::size_t object_count()
{
return 100;
}
protected :
static const std::size_t obj_count = 99 ;
};
class B : public A
{
public:
void f( B &b,B *b2)
{
cout << A::obj_count << endl;
cout << B::obj_count << endl;
cout << b.obj_count<< endl;
cout << b2->obj_count<< endl;
cout << obj_count<< endl;
cout << A::object_count() << endl;
}
};
int main(void)
{
B b;
b.f(b,&b);
return 0;
}
=================================================
#include <iostream>
#include <string>
using namespace std;
class Account
{
public:
Account(std::string name, double money):
owner(name),amount(money){}
double getAmount() const
{
return this->amount;
}
void applyint() { amount += amount*interestRate;}
void deposit(double money)
{
this->amount += money;
}
static double getRate() { return interestRate;}
static void rate(double newRate)
{
interestRate = newRate;
}
private:
std::string owner;
double amount;
static double interestRate ;
};
double Account::interestRate = 0.025;
int main()
{
Account a("zhang",1000);
Account b("li",2000);
Account::rate(0.34);
a.deposit(500);
b.deposit(600);
cout <<a.getAmount()<<endl;
cout <<b.getAmount()<<endl;
cout <<a.getRate()<<endl;
a.rate(0.025);
cout <<b.getRate()<<endl;
a.applyint();
b.applyint();
cout << a.getAmount() << endl;
cout << b.getAmount() << endl;
return 0;
}