Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a class in C++ so that it acts like a native int class

I am learning C++, and learned that int-types are just premade classes. So I thought maybe i should try to create one.

What I want to do basically is a normal class of int

int x;
x=7;
cout << x;

// Output is 7 on screen.

so similarly...

abc x;
x=7;
cout << x;

What would I put in

class abc{
\\ HERE!!!!!! 
};

so I could do this

class SomeClass {
public:
    int x;

    SomeClass(int x) {
        this->x = x;
    }
};

int main(int argc, char *argv[]) {
    SomeClass s = 5;

    cout << s.x << "\n"; // 5

    s = 17;

    cout << s.x << "\n"; // 17

    return 0;
}

But as you can see I have to use s.x to print the value - I just want to use 's'. I am doing it as an experiment, I don't want to hear about how this method is good or bad, pointless or revolutionary, or can 't be done. I remember once I did it. But only by copying and pasting code that I didn't fully understand, and have even forgotten about.

like image 219
Muhammad Umer Avatar asked Oct 16 '25 03:10

Muhammad Umer


2 Answers

and learned that int, types, are just premade classes

This is completely false. Still, you have complete control on how your class will behave in expressions, since you can overload (almost) any operator. What you are missing here is the usual operator<< overload that is invoked when you do:

cout<<s;

You can create it like this:

std::ostream & operator<<(std::ostream & os, const SomeClass & Right)
{
    Os<<Right.x;
    return Os;
}

For more information, see the FAQ about operator overloading.

like image 82
Matteo Italia Avatar answered Oct 17 '25 16:10

Matteo Italia


the << and >> are basically function names. you need to define them for your class. same with the +, -, * and all the other operators. here is how:

http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html

like image 24
Ionut Hulub Avatar answered Oct 17 '25 16:10

Ionut Hulub



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!