c++入门学习

c++入门-类

2018-11-09  本文已影响0人  昵称_7baf

一、类

#include <iostream>
using namespace std;

struct Person {
    int m_id;
    int m_age;
    int m_height;
    
    void display() {
        cout << "m_id" << m_id << endl;
        cout << "m_age" << m_age << endl;
        cout << "m_height" << m_height << endl;

    }
};

class Student {
    int m_id;
    int m_age;
    int m_height;
    
    void display() {
        cout << "m_id" << m_id << endl;
        cout << "m_age" << m_age << endl;
        cout << "m_height" << m_height << endl;
        
    }
};

int main(int argc, const char * argv[]) {
//    创建对象
    Person person;
    person.m_id = 10;
    person.m_age = 20;
    person.m_height = 30;
    person.display();
    
    Student student;
    student.m_id = 10;
    student.m_age = 20;
    student.m_height = 30;
    student.display();

    return 0;
}
示例.png

要想class声明的变量可以被访问,可以在前面加个public

class Student {
public:
    int m_id;
    int m_age;
    int m_height;
    
    void display() {
        cout << "m_id" << m_id << endl;
        cout << "m_age" << m_age << endl;
        cout << "m_height" << m_height << endl;
        
    }
};

二、C++编程规范(参考规范)

三、this

struct Person {
    int m_id;
    int m_age;
    int m_height;
    
    void display() {
        cout << "m_id " << this->m_id << endl;
        cout << "m_age " << this->m_age << endl;
        cout << "m_height " << this->m_height << endl;
        
    }
};

三、封装

class Teacher {
    
    int m_age;
    
public:
    void setAge(int age){
        this->m_age = age;
    }
    
    int getAge(){
        return this->m_age;
    }
};
    
    Teacher teacher;
    teacher.setAge(20);
    cout << teacher.getAge() << endl;

四、内存空间的布局

每个应用都有自己独立的内存空间,其内存空间一般都有以下几大区域 代码段(代码区)

内存布局

四、堆空间

五、memset

  Person person;
   person.m_id = 1;
   person.m_age = 10;
   person.m_height = 30;
   
   memset(&person, 0, sizeof(Person));

六、对象的内存

七、构造函数


struct Person {
    int m_age;
    
    Person(){
        cout << "Person()" << endl;
    }
    Person(int age){
        cout << "Person(int age)" << endl;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读