构造函数参数列表之后的结肠符号
The colon symbol after constructor parameter list
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.
}
相关文章:
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 将无符号char*转换为std::istream*C++
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 在类定义之后定义一个私有方法
- vscode g++链路故障:体系结构x86_64的未定义符号
- 在循环C++中指定字符串之后,不会打印该字符串
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何理解将半精度指针转换为无符号长指针和相关的内存对齐
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 使用gcc从静态链接的文件中查找可选符号
- C++宏忽略之后的内容
- 构造函数参数列表之后的结肠符号
- 按Enter在Enter之后,ReadConsoleInput仅读取第一个符号
- 为什么我们必须在箭头符号(->)之后再次指定数据类型
- 百分比符号之后的C 星号
- 数据类型之后或变量名称之前的引用符号之间的差异
- 在 Scala 2.9.3 编译器的擦除阶段之后获取具体类型的符号
- 静态无符号 int foo 和更高之后的 if ( foo >0 )?