C++转换与继承;友元friend与继承;静态成员与继承(六)

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值