help with Vector class question

Please help me answer this question.

Given the following class declaration of a Vector class, which works similar to those in math and includes a multiplication operator for scalars:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Vector{
  double* arr;
  int size;
  public:
    friend Vector operator * (double scalar, Vector v);

    Vector(double* values, int size) { 
      this->arr = values; 
      this->size = size; } 
};

//Multiplies the Vector by a scalar
Vector operator * (double scalar, Vector v) {
  double* newArr = new double[v.size];
  
  for(int i = 0; i < v.size; i++)
      newArr[i] = scalar * v.arr[i];

  return Vector(newArr, v.size);
}

int main() {
  double* values = new double[3];
  values[0] = 1.0;
  values[1] = 2.0;
  values[2] = 3.0;
  values(values, 3);

  Vector resultVector = exampleVector * 4.0;
}


What would be the results of the multiplication in main, i.e. what would be in values.arr? Think carefully.
 In function 'int main()':
27:19: error: 'values' cannot be used as a function
29:25: error: 'exampleVector' was not declared in this scope
29:10: warning: unused variable 'resultVector' [-Wunused-variable]
In other words: the code contains syntax errors. Nobody can compile it. Nobody can tell what values are in a program that does not exist.
Perhaps:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <initializer_list>
#include <algorithm>
#include <iostream>

class Vector {
	double* arr {};
	size_t size {};

public:
	friend Vector operator*(double scalar, const Vector& v);
	friend Vector operator*(const Vector& v, double scalar);
	friend std::ostream& operator<<(std::ostream& os, const Vector& v);

	Vector(double* values, size_t siz) : arr(values), size(siz) {}
	Vector(const std::initializer_list<double>& il) : size(il.size()), arr(new double[il.size()] {}) {
		std::copy(il.begin(), il.end(), arr);
	}

	Vector(const Vector&) = delete;
	Vector& operator=(const Vector&) = delete;

	~Vector() { delete[] arr; }
};

std::ostream& operator<<(std::ostream& os, const Vector& v) {
	for (size_t i = 0 ; i < v.size; ++i)
		os << v.arr[i] << ' ';

	return os << '\n';
}

//Multiplies the Vector by a scalar
Vector operator*(double scalar, const Vector& v) {
	auto newArr {new double[v.size]};

	for (size_t i = 0; i < v.size; ++i)
		newArr[i] = scalar * v.arr[i];

	return Vector(newArr, v.size);
}

Vector operator*(const Vector& v, double scalar) { return scalar * v; }

int main() {
	const auto exampleVector {Vector{1.0, 2.0, 3.0}};
	const auto resultVector {exampleVector * 4.0};

	std::cout << resultVector << '\n';
}



4 8 12

Topic archived. No new replies allowed.