C++中的成员变量是独立的,成员方法是共享的。


/// @file exam_1_1.cpp
/// @brief 1.通过写程序证明,C++中的成员变量是独立的,成员方法是共享的。

#include <iostream>
#include <limits>

using namespace std;

class CTest
{
public:
    CTest() {}
    ~CTest() {}

    void setter_iTest(int iIn) {m_iTest = iIn;}
    int getter_iTest() {return m_iTest;}
    int getAddr_iTest() {return (int)&m_iTest;}

private:
    int m_iTest;
};

void clear_cin();
void fnTestClass();

void fnEmptyFunction();

int main(int argc, char** argv, char** envp)
{
    fnTestClass();

    cout << "END, press any key to quit" << endl;
    clear_cin();
    getchar();

    return 0;
}

void fnTestClass()
{
    CTest t1;
    CTest t2;

    t1.setter_iTest(1);
    t2.setter_iTest(2);

    /// 通过写程序证明,C++中的成员变量是独立的,成员方法是共享的。
    cout << "t1.getAddr_iTest() = 0x" << hex << t1.getAddr_iTest() << endl;
    cout << "t2.getAddr_iTest() = 0x" << hex << t2.getAddr_iTest() << endl;

    cout << "t1.getAddr_iTest() " 
        << ((t1.getAddr_iTest() == t2.getAddr_iTest()) ? "== " : "!= ")
        << "t2.getAddr_iTest() " << endl;

    /** run result
    t1.getAddr_iTest() = 0x18fee0
    t2.getAddr_iTest() = 0x18fedc
    t1.getAddr_iTest() != t2.getAddr_iTest()
    */

    /// cout 打印不了函数指针
    /// http://stackoverflow.com/questions/2064692/how-to-print-function-pointers-with-cout
    printf("&CTest::getter_iTest = 0x%p\r\n", &CTest::getter_iTest);
    printf("t1.getter_iTest = 0x%p\r\n", t1.getter_iTest);
    printf("t2.getter_iTest = 0x%p\r\n", t2.getter_iTest);

    /** run result
    &CTest::getter_iTest = 0x0040115E
    t1.getter_iTest = 0x0040115E
    t2.getter_iTest = 0x0040115E
    */
}

void fnEmptyFunction()
{
    /// 空函数也是占空间的
}

void clear_cin()
{
    cin.clear();
    cin.sync();
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值