LearnFrenzy
Sign in Take a free test

Operator Overloading · Find the Error · Question 7

Error: inventing a new operator Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

main.cpp
#include <iostream>

struct Num {
    double v;
    Num operator**(int e) const {
        double r = 1;
        for (int i = 0; i < e; ++i) r *= v;
        return {r};
    }
};

int main() {
    Num n{2};
    std::cout << (n ** 10).v << '\n';
    return 0;
}
  • A e must be unsigned
  • B C++ has no ** operator, and new operators cannot be created; use a named function such as pow() Correct
  • C operator** must be a friend
  • D The loop is wrong
Correct Answer: Option B

Only existing operators can be overloaded.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links