C++练笔例子6类

#include <iostream>
using namespace std;
class C
{
      public:
             C(){cout << "chuangjiang C" << endl;}
             C(const C &other){cout << "coping C" << endl;}
             C & operator = (const C &other){cout << "= C" << endl;}
};
class B
{
      public:
             B(){cout << "chuangjiang B" << endl;}
             B(const B &other){cout << "coping B" << endl;}
             B & operator = (const B &other){cout << "= B" << endl;}
             int b;
};
class A
{
      public:
              A(){cout << "chuangjinag A" << endl;}
              A(const B &other):bb(other){cout << "chuangjinag A with B" << endl;}
              A(int i):b(i) {cout << "chuangjian A  with int" <<endl;}
              A(const A &other){cout << "coping A" << endl;}
              A & operator = (const A &other){cout << "= A" << endl;}
              int b;
              C cc;
              B bb;
              void useStatic(){
                   static B b;
                   cout << b.b<< endl;
              }
};

A & getRefence(A &a){
    return a;
}

A getValue(A &a){
    return a;   // 相当于 return A(a);
}

int main(){
    //非static成员变量是最早初始化的, 然后再运行构造函数, 
    A aa(2);
    cout << &aa << endl << endl;
   
    //返回值和返回引用的区别
    A bb;
    cout << "返回值和返回引用的区别: " << endl;
    bb = getValue(aa);
    cout << &bb << endl;
    bb = getRefence(aa);
    cout << &bb << endl << endl;
   
    //引用变量, java 声明的变量基本都是引用变量
    cout << "引用变量: " << endl;
    A &cc = getRefence(aa);
    cout << cc.b << " end" << endl << endl;
   
    //测试初始化表在什么时候进行, 可以调换 cc 和 bb 的位置测试
    //结果显示按成员变量的位置从上到下的顺序进行初始化, 不管是否在初始化表中
    B b;
    cout << "用B创建A: " << endl;
    A ab(b);
   
    //A c = A(1);
    //A d[2] = {A(1),A(1)};
    //A * e = new A[2];
    //cout << e[1].b <<endl;
   
    //测试局部static 变量
    cout  << endl << "test useStatic: " << endl;
    aa.useStatic();   
    aa.useStatic();
   
    cout << "sizeof B: " << sizeof(B) << endl;
    cout << "sizeof A: " << sizeof(A) << endl;
   
    system("pause");
}

 

测试了一下构造函数, 没有测试析构函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值