是的,你使用this->a = a;
另请注意,在 C++ 中,您应该在构造函数中使用初始化列表。
class Blab
{
public:
Blab(int a, int b)
:m_a(a),
m_b(b)
{
}
private:
int m_a;
int m_b;
};
编辑:
您可以:a(a), b(b)
在初始化列表中对数据成员 a 和传递给构造函数的参数 a 使用相同的名称。它们不必不同,但有些人认为对成员变量名称使用不同的命名约定是更好的做法。我在上面的示例中使用了不同的名称来帮助阐明初始化列表实际上在做什么以及它是如何使用的。如果您愿意,可以使用this->a
设置另一个成员变量。例如如果成员变量和参数变量都是a和b,
class MyClass
{
public:
MyClass(int a, int b);
private:
int a;
int b;
};
// Some valid init lists for the MyClass Constructor would be
:a(a), b(b) // Init member a with param a and member b with parameter b
:a(a), b(this->a) // Init member a with param a and init member b with member a (ignores param b)
:a(5), b(25) // Init member a with 5 and init member b with 25 (ignoring both params)
应该提到的是,初始化列表应该按照它们在类定义中出现的顺序来初始化成员变量。当你不这样做时,一个好的编译器会给你警告。