Reputation: 1528
Is it possible to overload a base type like char
or int
with extra operators?
What I tried:
bool char::operator[](const int param) {
if (param < 8) {
return (*this) & std::pow(2, param);
}
else {
exit(13);
}
}
What I want to happen:
I want the function to return the value of the bit at position param
of the character variable.
What Happens:
It does not compile. Error: 'bool' followed by 'char' is illegal.
Upvotes: 0
Views: 567
Reputation: 121
You can't overload char or use 'this' since it represents the instantiation of a class but what if you can create your own class Char or CHAR etc... similar to a String class or the way you can write Lists or Stacks using your own class using vectors. Here you go
So you can have something like
class Char{
private:
char cx;
public:
Char(){}
Char(char ctmp):cx(ctmp){}
Char(Char &tmp):cx(tmp.cx){ }
~Char(){ }
char getChar(void){ return this->cx; }
// operator implementations here
Char& operator = (const Char &tmp)
{
cx = tmp.cx;
return *this;
}
Char& operator = (char& ctmp){
cx = ctmp;
return *this;
}
bool operator[](const int param) {
if (param < 8) { return (*this) & std::pow(2, param); }
else { exit(13); }
}
};
Upvotes: 0
Reputation: 3083
No. char
is a fundamental type, and as such you cannot overload its member operator, as it has no members.
Furthermore, operator[]
cannot be implemented as a non-member function. So in this case, I am afraid you are out of luck.
Upvotes: 1