I'm moving from C to C++ and I don't get t

2019-07-08 02:36发布

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; 
};

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?

标签: c++ class
2条回答
迷人小祖宗
2楼-- · 2019-07-08 03:27

The last {} is the body of the constructor. Methods dont need a ; at the end. The stuff before is the initializer list:

Vector(int s) :elem{new double[s]}, sz{s} { }
            // ^^ initializer list        ^^ body of the constructor

This could also be written as

Vector(int s) {                 // no initializer list, but still 
                                // members are initialized here already
    elem = new double[s];
    sz = s;
}                               // no ; here  !!

but then the member are initialized and then assigned a value.

查看更多
爷、活的狠高调
3楼-- · 2019-07-08 03:31

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
};

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 ;.

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.

查看更多
登录 后发表回答