c++面向对象模型---c++如何管理类,对象以及它们之间的联系

首先我们随意定义4个类结构

class cl1
{
private:
    int age;
    string name;
    static  int addr;
public:
    cl1()
    {

    }
    void iwasthelastlivingsoul()
    {

    }
    int getage()
    {
        return this->age;
     }
}; //32
class cl2
{
private:
    int age;
    string name;
public:
    cl2()
    {

    }
    void iwasthelastlivingsoul()
    {

    }
    int getage()
    {
        return this->age;
    }
};//
class cl3
{
private:
    string name;
public:
    cl3()
    {

    }
    void iwasthelastlivingsoul()
    {

    }
    int getage()
    {
    }
};
class cl4
{
private:
    string name;
public:
    cl4()
    {
    }
    ~cl4()
    {
    }
};
  • 主程序
void main()
{
    cl1 c1;
    cout << sizeof(c1) << endl;
    cl2 c2;
    cout << sizeof(c2) << endl;
    cl3 c3;
    cout << sizeof(c3) << endl;
    cl4 c4;
    cout << sizeof(c4) << endl;
    system("pause");
}

输出结果:

32
32
28
28
请按任意键继续. . .

由此可见 string类型占据了28个字节。这是个伟大发现,因为至少我读的C++教材里没有介绍的,哦哈哈哈哈

不信?那再试试

class cl5
{
private:
    string name;
    string favorite;
public:
    cl5()
    {
    }
    ~cl5()
    {
    }
};

void main()
{
    cl5 c5;
    cout << sizeof(c5) << endl;
    system("pause");
}

56
请按任意键继续. . .

言归正传,由cl1和cl2的大小比较 static int静态整型实际上放在了全局变量区而并不占用类声明的空间,而那些成员函数应该就放在代码去了,只有运行时才分配内存

  • 不同类对象调用相同成员方法如何做到互不干扰呢
#include<iostream>
#include<string>
using namespace std;
class cl1
{
private:
    int age;
    string name;
    static  int addr;
public:
    cl1(string name)
    {
        this->name = name;
    }
    void iwasthelastlivingsoul()
    {
        cout << "hello,I'm " <<this->name<< endl;
    }
    int getage()
    {
        return this->age;
     }
};


void main()
{
    cl1 c1("陈培昌");
    c1.iwasthelastlivingsoul();
    cl1 c2("徐晓冬");
    c2.iwasthelastlivingsoul();
    cl1 c3("付高峰");
    c3.iwasthelastlivingsoul();
    system("pause");
}

输出结果:

hello,I'm 陈培昌
hello,I'm 徐晓冬
hello,I'm 付高峰
请按任意键继续. . .

这是由于C++类中,普通成员函数包含一个指向具体对象的指针,而静态成员函数不包括。

静态成员变量和静态成员函数属于类(而不是对象),静态成员函数不含指向具体对象的指针

猜你喜欢

转载自www.cnblogs.com/saintdingspage/p/12031984.html