在以下C++代码中:
struct Features {
int F1;
int F2;
int F3;
int F4;
Features(int F1,int F2,int F3,int F4)
: F1(F1), F2(F2), F3(F3), F4(F4) { }
};
Run Code Online (Sandbox Code Playgroud)
这部分是什么意思?
Features(int F1,int F2,int F3,int F4)
: F1(F1), F2(F2), F3(F3), F4(F4) { }
Run Code Online (Sandbox Code Playgroud)
谢谢.
它使用构造函数的初始化列表初始化成员变量.如果构造函数参数的名称与数据成员不同,那将更清楚:
Features(int a,int b,int c,int d)
: F1(a), F2(b), F3(c), F4(d) { }
Run Code Online (Sandbox Code Playgroud)
为数据成员设置一些命名约定很有用,这样可以很容易地识别它们,并且可以与代码中的局部变量区分开来.示例是前缀m_或使用尾部_:
struct Features {
int m_f1;
int m_f2;
int m_3f;
int m_f4;
Features(int f1,int f2,int f3,int f4)
: m_f1(f1), m_f2(f2), m_f3(f3), m_f4(f4) { }
};
Run Code Online (Sandbox Code Playgroud)
这两个构造函数都可以像这样使用:
Features f(11,22,33,44);
std::cout << f.m_f1 << "\n"; // prints 11
std::cout << f.m_f2 << "\n"; // prints 22
std::cout << f.m_f3 << "\n"; // prints 33
std::cout << f.m_f4 << "\n"; // prints 44
Run Code Online (Sandbox Code Playgroud)
请注意,已定义此构造函数的事实意味着编译器将不再提供默认构造函数.所以如果你想能够这样:
Features f;
Run Code Online (Sandbox Code Playgroud)
那么你需要提供自己的默认构造函数:
Features() : m_f1(), m_f2(), m_f3(), m_f4() {} // initializes data members to 0
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
131 次 |
| 最近记录: |