简体   繁体   中英

Explain C++ code

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 .

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM