How to implement a 𝙲++ 𝚌𝚕𝚊𝚜𝚜 that allows 𝚡 ** 𝚢 syntax to call 𝚙𝚘𝚠(𝚡, 𝚢) (Urdu / Hindi)

x ** y in C++

In this C++ programming tutorial, we are going to learn how to implement a cpp 𝚌𝚕𝚊𝚜𝚜 and use operator overloading to allow a syntax like 𝚡 ** 𝚢 call the 𝚜𝚝𝚍::𝚙𝚘𝚠(𝚡, 𝚢) function and return the result, where 𝚡 is of type 𝚍𝚘𝚞𝚋𝚕𝚎 and 𝚢 is a custom 𝚌𝚕𝚊𝚜𝚜 object 𝙴𝚡𝚙𝚘𝚗𝚎𝚗𝚝.

Statement: 

Define a class Exponent to hold a real exponent for an exponentiation operation. Through clever use of operator overloading, find a way to have the expression x ** y call std::pow(x, y), where the types of x and y are double and Exponent, respectively. In other words, the program listed below when executed would output the value 16 (i.e., 24 = 16).

Series playlist ▶︎ https://youtube.com/playlist?list=PLt4rWC_3rBbWnDrIv4IeC4Vm7PN1wvrNg 

Source Code:

#include <iostream>
#include <cmath>
#include <utility>

class Exponent {
private:
    double y{};
    friend double operator*(double x, Exponent& y);
    friend std::ostream& operator<<(std::ostream& cout, const Exponent&);
public:
    explicit Exponent(double y) : y{y} {}
    Exponent& operator*() { return *this; }
    const Exponent& operator*() const { return *this; }

    double operator*(double y) const {
        return std::pow(this->y, y);
    }

};

double operator*(double x, Exponent& y) {
    return std::pow(x, y.y);
}


int main() {
//    double x{12.};
//    Exponent y{.5};
//    double result{x ** y}; // 4 ^ 3
//
//    std::cout << x << " ^ " << y << " = " << result << std::endl;

    double number{2.6};
    double* x{&number};
    const Exponent y{6};

    auto result{ y ** x }; // 10 ^ 2
//    auto result{ y ** (&(double&)(double&&)(2.5)) }; // 10 ^ 2
    std::cout << "result = " << result << std::endl;


}


std::ostream& operator<<(std::ostream& cout, const Exponent& exponent) {
    cout << exponent.y;
    return cout;
}

Watch The Video:

Post a Comment

0 Comments