Answered step by step
Verified Expert Solution
Question
1 Approved Answer
please solve my doubts and explain in detail for questions written in red, answer is provided 4. Classes and function operator overloading: (a) For the
please solve my doubts and explain in detail for questions written in red, answer is provided
4. Classes and function operator overloading: (a) For the MathVector class above, show how the square brackets operato (indexing operator) can be overloaded to return a given indexed element Should this operator be a class member function, and if so will it be private or public? (b) Explain how the * operator can be overloaded to enable expressions such as av, va, and u* v (which we take to mean the cross-product, which you need only implement for 3-vectors), where u and v are vectors and a is a scalar. a 1 class MathVector { public: // constructors and other public interface goes here 2 1 6 7 double koperator [] (int i) { return elements[i]; } private: // private data std::vector elements; int length; 10 11 12 Listing 5: Indexing operator for MathVector celumny posterende bon the time your home easy understanding wory Note that we return a reference to the ith element. This means the indexing operator || behaves exactly as for an array. We could alternatively return just ? a double (not a reference), which would mean we could access the element values, but not set them: mv[i] would be a valid value in a normal expression (e.g. double val = mv[i]*10.0;), but we could not use it in an assignment, viz mv[i] = 10.0;. It should probably) be a class member function as this is more compatible with traditional notation: we don't see the indexing operator as modifying the instance. The overloaded operator must be public otherwise the outside program could not use it. 1 13 MathVector operator+(const double alpha, Mathvector &m) { // pass m by reference, as it might be big! MathVector retval(m); // use the Math Vector copy // constructor: we don't want to // accidentally modify , to which we 1/ have access via the reference. for (int i = 0; i } return retval; 27 9 10 12 13 14 15 16 MathVector operator*(Mathvector &m, const double alpha) { MathVector retval(m); for (int i = 0; i Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started