为了避免在C++中使用成员初始化列表时的错误,请遵循以下建议:
class MyClass {
public:
int x;
double y;
MyClass(int a, double b) : x(a), y(b) {}
};
class MyClass {
public:
int x;
double y;
MyClass() : x(0), y(0.0) {}
};
class MyClass {
public:
const int x;
double y;
MyClass(int a) : x(a), y(0.0) {}
};
class MyClass {
public:
MyClass(int a, int b);
private:
int x;
int y;
};
MyClass::MyClass(int a, int b) : x(a), y(b) {}
class MyClass {
public:
int x = 0;
double y = 0.0;
MyClass(int a, double b) : x(a), y(b) {}
};
class MyClass {
public:
int x;
double y;
MyClass(int a, int b) : x(a + b), y((double)a / b) {}
};
遵循这些建议,可以帮助您避免在C++中使用成员初始化列表时的错误。