问题
Possible Duplicates:
C++ weird constructor syntax
Variables After the Colon in a Constructor
What does a colon ( : ) following a C++ constructor name do?
For the C++ function below:
cross(vector<int> &L_, vector<bool> &backref_, vector< vector<int> > &res_) :
L(L_), c(L.size(), 0), res(res_), backref(backref_) {
run(0);
}
What does the colon (":") tell the relationships between its left and right part? And possibly, what can be said from this piece of code?
回答1:
This is a way to initialize class member fields before the c'tor of the class is actually called.
Suppose you have:
class A {
private:
B b;
public:
A() {
//Using b here means that B has to have default c'tor
//and default c'tor of B being called
}
}
So now by writting:
class A {
private:
B b;
public:
A( B _b): b(_b) {
// Now copy c'tor of B is called, hence you initialize you
// private field by copy of parameter _b
}
}
回答2:
It's a member initialization list.
You're setting each of the member variables to the values in parentheses in the part after the colon.
回答3:
Like many things in C++, :
is used for many things, but in your case it is the start of an initializer list.
Other uses are for example after public/private/protected, after a case label, as part of a ternary operator, and probably some others.
来源:https://stackoverflow.com/questions/3504215/what-does-the-colon-mean-in-a-constructor