So this might be a silly question but I couldn't find any solution online.
I was reading the book "A Tour of C++" by Bjarne Stroustrup and I tried to follow Section 2.3.2. We first defined a class called Vector:
#include <iostream>
class Vector {
public:
Vector(int s) :elem{new double[s]}, sz{s} { } // constr uct a Vector
double& operator[](int i) {return elem[i]; } // element access: subscripting
int size() { return sz; }
private:
double* elem; // pointer to the elements
int sz; // the number of elements
};
Then we wrote a read_and_sum function:
Vector v(6); // a Vector with six elements
double read_and_sum(int s)
{
Vector v(s); // make a vector of s elements
for (int i=0; i<v.size(); ++i) std::cin>>v[i]; // read into elements
double sum = 0;
for (int i=0; i<v.size(); ++i) sum+=v[i]; // take the sum of the elements
return sum;
}
I wrote the main() to print out the sum and the elements in my vector:
int main(){
std::cout << read_and_sum(6); \\print the sum
for (int i=0; i<v.size(); ++i) std::cout<< v.operator[](i) << "\n"; \\print each value in vector
After I run the program, I input six numbers first and I saw the correct sum. But I got 6 crazy numbers like 646.82957e-318 when I tried to print the number I just entered. What did I do wrong?