课后作业3、类和对象(填空题)

4-1

有如下定义语句:“sample s[10];”sample为某种类的类名,则系统自动调用该类构造函数10

次。 当类对象数组s离开它的作用域时,系统自动调用该类析构函数  10次。


4-2

下面程序运行结果为 3

#include <iostream>
#include <string.h>
using namespace std;
class Toy
{
        public:
            Toy(char* _n) { strcpy (name,_n); count++;}
            ~Toy(){ count--; }
            char* GetName(){ return name; }
            static int getCount(){ return count; }
        private:
            char name[10];
            static int count;
};
int Toy::count=0;
int main()
{
        Toy t1("Snoopy"),t2("Mickey"),t3("Barbie");
        cout<<t1.getCount()<<endl;
        return 0;
}

4-3

下面程序的运行结果。

#include <iostream>
using namespace std;
class B
{
    public:
        B(){cout<<++b<<endl;}
        ~B(){cout<<--b<<endl;}
        static int Getb(){return b;}
    private:
        static int b;
};
int B::b=10;
int main()
{
    B b1,b2,b3;
    cout<<B::Getb()<<endl;
    return 0;
}

程序结果为:

11

12

13

13

12

11

10


4-4

有如下程序:请写出程序输出结果。

class Test
{
public:
    Test(){cout<<"构造函数"<<endl;}        
    ~Test(){cout<<"析构函数"<<endl;}    
};
void myfunc(){
    static Test obj;
}
int main()
{
    cout<<"main开始"<<endl;
    myfunc();
    cout<<"main结束"<<endl;
    return 0;
}

main开始

构造函数

main结束

析构函数


4-5

写出下面程序的运行结果。

#include<iostream>
using namespace std;
class A
{
    public:
        A(int i){a=i;}
        void print()
        {    cout<<"a="<<a<<endl;
            cout<<"this->a="<<this->a<<endl;
        }
    private:
        int a;
};
int main()
{
    A x(55);
    x.print();
    return 0;
}

运行结果为:

a=55

this->a=55


4-6

在C++中,每个类都有一个隐含的指针叫做  this

指针,该指针指向正在被成员函数操作的对象。


4-7

这是一个有关使用this指针返回对象和返回对象引用的程序题。该程序中显示定义了拷贝构造函数。
读程序分析输出结果。

#include <iostream>
using namespace std;
class A{
private:
    int m;
public:
    A():m(1){cout<<"默认构造函数"<<endl;}
    ~A(){cout<<"析构函数"<<endl;}
    A(const A &b){
        m=b.m; 
        cout<<"拷贝构造函数"<<endl;
    }
    A fun1(){
        cout<<"m="<<m<<endl;
        return *this; 
    }
    A &fun2(){
        cout<<"m="<<m<<endl;
        return *this; 
    }
    void set(int x){m=x;}
    void display(){
        cout<<"m="<<m<<endl;
    }
};
int main(){
    cout<<"==返回对象=="<<endl;
    A a1;
    a1.fun1().set(2);
    a1.display();
    cout<<"==返回引用=="<<endl;
    A a2;
    a2.fun2().set(2);
    a2.display();
    return 0; 
} 

==返回对象==

默认构造函数

拷贝构造函数

析构函数

==返回引用==

默认构造函数

析构函数

析构函数

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

102101222_张凯权

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值