构造函数正在初始化数据成员



我是c++编程的新手。这是Bjarne Stroustrup的c++书中的一个例子。有人能向我解释一下这条线是干什么的吗

X(int i =0) :m{i} { } //a constructor ( initialize the data member m )

有人能告诉我这个":"符号的作用吗。我是c++程序的新手。

class X { 
private: //the representation (implementation) is private
int m;
public: //the user interface is public
X(int i =0) :m{i} { } //a constructor ( initialize the data memberm )
int mf(int i) //a member function
{
int old = m;
m = i; // set new value
return old; // return the old value
}
};
X var {7}; // a variable of type X initialized to 7
int user(X var, X∗ ptr) {
int x = var.mf(7); //    access using . (dot)
int y = ptr−>mf(9); //   access using -> (arrow)
int z = var.m; //error : cannot access private member
}
初始化器列表用于初始化类的数据成员。要初始化的成员列表用构造函数表示为逗号分隔的列表,后跟冒号。
#include<iostream> 
using namespace std; 
class Point { 
    int x; 
    int y; 
public: 
    Point(int i = 0, int j = 0) : x(i), y(j) {}  
    /*  The above use of Initializer list is optional as the  
        constructor can also be written as: 
        Point(int i = 0, int j = 0) { 
            x = i; 
            y = j; 
        } 
    */    
    int getX() const {return x;} 
    int getY() const {return y;} 
}; 
int main() { 
  Point t1(10, 15); 
  cout << "x = " << t1.getX() << ", "; 
  cout << "y = " << t1.getY(); 
  return 0; 
} 
/* OUTPUT: 
   x = 10, y = 15 
*/

上面的代码只是Initializer列表语法的一个示例。在上面的代码中,x和y也可以很容易地在构造函数中初始化。但在某些情况下,构造函数内的数据成员初始化不起作用,必须使用Initializer List。以下是此类情况:

1( 对于非静态常量数据成员的初始化:const数据成员必须使用Initializer List进行初始化。在以下示例中,"t"是Test类的常量数据成员,并使用Initializer List进行初始化。初始化初始化器列表中的常量数据成员的原因是,没有为常量数据成员单独分配内存,它被折叠在符号表中,因此我们需要在初始化器列表中将其初始化。此外,它是一个复制构造函数,我们不需要调用赋值运算符,这意味着我们避免了一个额外的操作。

最新更新