c ++ c ++ object-oriented model --- how management classes, objects and the links between them

First, we arbitrarily define four class structure

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()
    {
    }
};
  • The main program
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");
}

Output:

32
32
28
28
Press any key to continue...

Thus string type occupies 28 bytes. This is a great discovery, because at least I read the textbooks in C ++ did not introduce, oh ha ha ha ha

Do not believe? Try it again

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

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

56
Press any key to continue...

Closer to home, the size of the cl1 and cl2 relatively static int static int actually put the global variable area and do not take up space in the class declaration, and those members of the function should be placed on the code to allocate memory only when you run

  • Different members of the same class object calls the method how to do it without disturbing each other
#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;
    }
    intgetAge () 
    { 
        return  the this -> Age; 
     } 
}; 


void main () 
{ 
    CLl C1 ( " Chen Peichang " ); 
    c1.iwasthelastlivingsoul (); 
    CLl C2 ( " Xu Xiaodong " ); 
    c2.iwasthelastlivingsoul (); 
    CLl C3 ( " Fugao Feng " ); 
    c3.iwasthelastlivingsoul (); 
    System ( " PAUSE " ); 
}

Output:

hello, I'm Chenpei Chang
hello, I'm Xu Xiaodong
hello, I'm Fu Gaofeng
Press any key to continue...

This is due to a C ++ class, member function ordinary concrete contains a pointer to the object, but does not include a static member functions.

Static member variables and static member functions belonging to class (rather than the object), directed to a particular free of static member function pointer to an object

Guess you like

Origin www.cnblogs.com/saintdingspage/p/12031984.html