类-C++编程规范

  • C++可以使用struct、class来定义一个类
    struct在C语言中叫结构体
#include <iostream>
using namespace std;

//定义类
struct Person {
    //成员变量(属性)
    int age;
    //成员函数(方法)
    void run() {
        cout << "Person::run() - " << age << endl;
  }
};

int main() {

    //使用类来创建对象
    Person person;      //Person person = new Person(); java是这样
    person.age = 10;
    preson.run();

    getchar();
    return 0;
}
  • struct和class的区别
    struct的默认成员和函数权限是public
    class的默认成员和函数权限是private
struct Person {
private:        //下面的都生效
    //成员变量(属性)
    int age;
    //成员函数(方法)
    void run() {
        cout << "Person::run() - " << age << endl;
  }
};
class Person {
public:        //下面的都生效
    //成员变量(属性)
    int age;
    //成员函数(方法)
    void run() {
        cout << "Person::run() - " << age << endl;
  }
};

C++编程规范

  • 没有标准答案,也没有最好的编程规范,都是自己的编程规范
    全局变量:g_
    成员变量:m_
    静态变量:s_
    常量:c_
    驼峰标识

对象、指针的内存都是在函数的栈空间,自动分配和回收

void test() {
Person person;
person.m_age = 20;
person.run();

Person *P = &person;
p->m_age = 30;
p->run();
}

int main() {
    test();
}

查看struct和class的反汇编,无区别

原文地址:https://www.cnblogs.com/sec875/p/12264797.html