windows实验3——c++

1、getline的使用

#include <iostream>
#include<string>

using namespace std;

int main()
{
    for(int i=0;i<2;i++){
        string city,state;
        getline(cin,city,',');
        getline(cin,state);
        cout<<"City:"<<city<<"  State:"<<state<<endl;
    }
    return 0;
}

结果:

Beijing,China
City:Beijing  State:China
San Francisco,the Unite States
City:San Francisco  State:the Unite States

2、类的继承

1、类型兼容规则实例

#include <iostream>

using namespace std;

class Base1 {
public:
    void display() const {cout<<"Base1::display()"<<endl;}
};

class Base2:public Base1 {
public:
    void display() const {cout<<"Base2::display()"<<endl;}
};

class Derived:public Base2 {
public:
    void display() const {cout<<"Derived::display()"<<endl;}
};

void fun(Base1 *ptr){
    ptr->display();
}

int main()
{
    Base1 base1;
    Base2 base2;
    Derived derived;

    fun(&base1);
    fun(&base2);
    fun(&derived);

    return 0;
}

结果:

Base1::display()

Base1::display()

Base1::display()

用基类的指针指向子类的对象,然后调用成员函数,只能够调用基类的成员函数而不是子类的成员函数。

2、派生类构造函数

#include <iostream>

using namespace std;

class Base1 {
public:
    Base1(int i){cout<<"Constructing Base1 "<<i<<endl;}
    ~Base1(){cout<<"Destructing Base1"<<endl;}
};
class Base2{
public:
    Base2(int i){cout<<"Constructing Base2 "<<i<<endl;}
    ~Base2(){cout<<"Destructing Base2"<<endl;}
};
class Base3{
public:
    Base3(){cout<<"Constructing Base3 *"<<endl;}
    ~Base3(){cout<<"Destructing Base3"<<endl;}
};

class Derived:public Base2,public Base1,public Base3 {
public:
    Derived(int a,int b,int c,int d):Base1(a),member2(d),member1(c),Base2(b){}
private:
    Base1 member1;
    Base2 member2;
    Base3 member3;
};

int main()
{
    Derived obj(1,2,3,4);
    return 0;
}

结果:

Constructing Base2 2

Constructing Base1 1

Constructing Base3 *

Constructing Base1 3

Constructing Base2 4

Constructing Base3 *

Destructing Base3

Destructing Base2

Destructing Base1

Destructing Base3

Destructing Base1

Destructing Base2

先调用基类的构造函数,再调用内嵌对象的构造函数。

基类构造函数的调用顺序是按照派生类定义时的顺序,而内嵌对象的构造函数的调用顺序是按照成员在类中声明的顺序。

在执行析构函数是,执行顺序与构造函数完全相反。





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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值