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

来源:互联网 发布:龙岗网络推广szaow 编辑:程序博客网 时间:2024/05/16 08:51


/// @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();}




0 0