Skip to content

Latest commit

 

History

History
59 lines (45 loc) · 981 Bytes

025-构造函数.md

File metadata and controls

59 lines (45 loc) · 981 Bytes

025-构造函数

c++里面的构造函数的具体思路和Java差不多

#include <iostream>

class Entity {
public:
    float mX;
    float mY;

    Entity() {
        mX = 5;
        mY = 6;
    }

    Entity(float x, float y) {
        mX = x;
        mY = y;
    }

    void print() {
        std::cout << mX << "," << mY << endl;
    }
};

int main() {
    Entity entity(9, 8);
    entity.print();
    return 0;
}

如果需要私有化构造函数,private即可,建议还是使用删除构造函数(Clang-Tidy: Use '= delete' to prohibit calling of a special member function)

class Entity {
private:
    Entity();
};

或者使用删除构造函数

class Entity {
public:
    float mX;
    float mY;
    Entity() = delete;
};

这个删除构造函数需要最好是public(Clang-Tidy: Deleted member function should be public)


https://www.bilibili.com/video/BV1Hz4y1r7r2