Explain C++ code

2020-04-01 06:14发布

Can I get some help with explanation of the following code?

#include <iostream>

class Vector {
    private:
        double∗ elem; // pointer to the elements
        int sz;       // the number of elements
    public:
        Vector(int s) :elem{new double[s]}, sz{s} { }
        double& operator[](int i) { return elem[i]; }
        int size() { return sz; }
};

I am trying to brush up my C++ knowledge, but this syntax seems very new to me.

More specifically the code under public.

标签: c++ c++11
3条回答
我只想做你的唯一
2楼-- · 2020-04-01 06:42
Vector(int s) :elem{new double[s]}, sz{s} { }

It is the constructor. It is required an int parameter for instantiating.

elem{new double[s]}, sz{s} { }

This part describes how to initiate the member variables. An array type of double named elem. emem has "s" length array. sz is set as "s".

double& operator[](int i) { return elem[i]; }

This part is in order for access by element index.

Vector v(1);
return v[0]; // <= return double reference

I will share an example. This is introduced in The C++ Programming Language (4th Edition) written by Bjarne Stroustrup

#include <iostream>

using namespace std;

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

double read_and_sum(int s)
{
    Vector v(s);
    for (int i=0; i!=v.size(); ++i)
        cin >> v[i];

    double sum = 0;
    for (int i=0; i!=v.size(); ++i)
        sum += v[i];

    return sum;
}

int main() {
    int sum = read_and_sum(3);
    cout << sum << endl;
}
查看更多
够拽才男人
3楼-- · 2020-04-01 06:47

Maybe it's the new C++11 initialisation-lists that are confusing you, you now can initialise a variable with curly-braces {}. For example:

int i{42};
std::vector<int> v{1, 2, 3, 4};

everything else in your code looks pretty standard pre-C++11

查看更多
爷、活的狠高调
4楼-- · 2020-04-01 06:53

Vector(int s) defines a constructor - a special method that is called when object is created.

:elem{new double[s]}, sz{s} is a initializer list - it initializes object's fields. The whole part:

Vector(int s):elem{new double[s]}, sz{s} {}

Works same as

Vector(int s) {    
elem = new double[s];
sz = s;
}

However, initializer lists can be used to initialize constants and references.

查看更多
登录 后发表回答