我正在从C转到C ++,但没有得到这个类的创建 [英] I'm moving from C to C++ and I don't get this creation of a class
问题描述
我是C开发人员,所以我决定转向c ++作为主要语言,以扩大我的视野.通过"C ++编程语言"的研究,我看到了创建类的示例:
I'm a C developer and I decided to move to c++ as main language to enlarge my horizons. Studying from "The C++ Programming Language" I saw this example of the creation of a class:
class Vector {
public:
Vector(int s) :elem{new double[s]}, sz{s} { }
double& operator[](int i) { return elem[i]; }
int size() { return sz; }
private:
double* elem;
int sz;
};
我没有使用sz {s} {}
And I don't get the use of sz{s} { }
我们为什么使用 {}
?为什么在行尾没有;
?
Why do we use the {}
? Why there is not ;
at the end of the line?
推荐答案
由于延迟缩进.让我们写得更清楚:
Because of lazy indentation. Let's write it clearer:
class Vector
{
private:
double* elem;
int sz;
public:
Vector(int s)
: elem{new double[s]}
, sz{s}
{
// ctor body
}
// More class members
};
看到了吗?您神秘的 {}
只是构造函数的主体,而只是函数主体,就像在C语言中一样,函数并不以;
结尾.
See? Your mysterious {}
are just the body of the constructor, that is just a function body, and as in C, functions do not end with a ;
.
以:
开头的怪异行是初始化列表,其中初始化成员变量和基类,也就是在其中将参数写入其构造函数的地方. sz {s}
只是此列表中的第二个元素.
The weird lines beginning with :
is the initialization list, where member variables and base classes are initialized, that is where you write the areguments to their constructors. The sz{s}
is just the second element in this list.
这篇关于我正在从C转到C ++,但没有得到这个类的创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!