我是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
}
答案 0 :(得分:1)
初始化器列表用于初始化类的数据成员。构造函数将要初始化的成员列表表示为逗号分隔的列表,后跟冒号。
#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也可以在构造函数中轻松初始化。但是在某些情况下,无法初始化构造函数中的数据成员,而必须使用“初始化列表”。以下是这种情况:
1)对于非静态const数据成员的初始化: const数据成员必须使用初始化列表初始化。在以下示例中,“ t”是Test类的const数据成员,并使用初始化列表进行初始化。在初始化列表中初始化const数据成员的原因是因为没有为const数据成员单独分配内存,因此将其折叠在符号表中,因此我们需要在初始化列表中对其进行初始化。 另外,它是一个复制构造函数,我们不需要调用赋值运算符,这意味着我们避免了一个额外的操作。