0

so basically I'm just sand boxing around with c++ because I'm trying to learn some but when I created a class I quickly found out that using classType className=value; will create the class using an overloaded constructor

how do I make it so my class can use other operators like *, == or ||

like i know in python you create private methods like __plus__ is it something similiar in c++?

user1895629
  • 147
  • 1
  • 1
  • 8

2 Answers2

1

You can overload a lot of operators in C++. In your case you just have to declare functions with the name operator*, operator== and operator|| respectively. Some operators might need to be overloaded as member functions of the class, other as free functions.

Here's some function signature examples:

X operator*(const X&, const X&);
bool operator==(const X&, const X&);
bool operator||(const X&, const X&);

You can easily find a complete list of overloadable operators on Wikipedia.

Before going into this topic, I suggest you to pick a good book and learn a little bit more of C++. Some operators might be dangerous to overload without the proper precautions and some might not behave the way you expect once overloaded.

Community
  • 1
  • 1
Shoe
  • 74,840
  • 36
  • 166
  • 272
  • 1
    The poster should know that overloaded `operator||` does not act like the normal `||`. It does not short-circuit. Both arguments are calculated. – Eric Jablow Oct 18 '13 at 01:27
0

Look up overloading operators.

Here are some links that you can use.

http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html
http://www.cplusplus.com/doc/tutorial/classes2/
Operator overloading

The first two are about how to do it, the third is on why/when.

Community
  • 1
  • 1
Shade
  • 775
  • 3
  • 16