C++基础之初始化列表

    科技2024-10-07  17

        Initializer list

    #include <iostream> using namespace std; class Point { private: const float x, y; Point(float xa = 0.0, float ya = 0.0) :y(ya), x(xa) {} };

        ◆ Can initialize any type of data

            — pseudo-constructor calls for built-ins

            — No need to perform assignment within body of constructor

        ◆ Order of initialization is order of declaration

            — Not the order in the list!

            — Destroyed in the reverse order.

        Initialization vs. assignment

    Student::Student(string s): name(s) {}

        initialization

        before constructor

    Student::Student(string s) {name = s;}

        assignment

        inside constructor

        string must have a default constructor

    【例】

    #include <iostream> using namespace std; class A { public: A(int i) {} }; class B { public: A a; B() { a = 0; } };

        以上代码会报错:类 "A" 不存在默认构造函数。上例的错误揭示我们在初始化类的对象时,建议使用初始化列表,而不是在构造函数中进行赋值

    Processed: 0.009, SQL: 8