Explain C++ code

后端 未结 3 1076
执念已碎
执念已碎 2021-01-17 06:11

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

#include 

class Vector {
    private:
        double∗ elem; // pointer to the el         


        
相关标签:
3条回答
  • 2021-01-17 06:37

    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.

    0 讨论(0)
  • 2021-01-17 06:43

    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

    0 讨论(0)
  • 2021-01-17 06:44
    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;
    }
    
    0 讨论(0)
提交回复
热议问题