class Sales_data {
public:
Sales_data(int i, int j, int k) : x(i), y(j), z(k) {
}
private:
int x,y,z;
};
在上面的代码中(更具体地说,在sales_data构造函数中(以下内容((,我不明白Colon和Comma分离列表的使用。
Sales_data(int i, int j, int k) : x(i), y(j), z(k) {
}
我从未见过任何功能/构造函数参数列表之后的结肠(; quot;;此结肠在这里意味着什么?
此外,在结肠之后,这个逗号分开的列表是什么?
您可能会感到困惑,因为成员变量名称(x(与函数参数(也是X(相同,您可以始终避免为了清楚起见。简化的代码看起来像是如此。
add_x(int x1) : x(x1) // a contructor that initializes the member vaiable x to x1
{
}
仍然困惑吗?那么您可以选择这个(虽然不是那么优化(
add_x(int x1)
{
x = x1;
}
这是一个构造函数
这不是标准函数/方法。每个类(struct(可以具有构造函数。构造函数具有与类相同的名称,并且可以选择为参数。
struct add_x {
int x;
add_x(int x) : x(x) {} // This is a constructor with one paramter
};
使我们更容易阅读,让我们更好地格式化。
struct add_x {
int x;
add_x(int x) // Constructor that takes one argument.
: x(x) // This is called the initializer list.
{} // This is the body of the constructor.
};
初始化列表允许您在执行构造函数之前列出成员变量(逗号分隔(并初始化它们。
在这种情况下,成员x
用参数x
初始化。
#include <iostream>
int main()
{
add_x test(5);
std::cout << test.x << "n"; // Should print 5
// Note in my example I have removed the private
// section so I can read the value x.
}