2016-05-15 69 views
-1

是否有可能超载基本类型像charint有额外的运营商?重载基本数据类型

我试了一下:

bool char::operator[](const int param) { 
    if (param < 8) { 
     return (*this) & std::pow(2, param); 
    } 
    else { 
     exit(13); 
    } 
} 

我想发生: 我希望函数在字符变量的param位置返回该位的值。

发生了什么: 它不能编译。错误:'bool' followed by 'char' is illegal.

+1

问题。最后回答。是否需要详细说明。 –

+0

'^'是按位异或运算符。我相信你正在寻找逐字分解(“和”),写成'&'。 'pow'返回一个浮点值;如果你想计算2到一个小整数的幂,使用左移运算符:1U << param'(或者'1UL << param',如果你期望'param'大于' int'。甚至'1ULL << param' ...) – rici

回答

1

char是基本类型,因此您不能重载其成员运算符,因为它没有成员。

此外,operator[]不能被实现为一个非成员函数。所以在这种情况下,我担心你运气不好。

0

你不能重载char或使用“本”,因为它代表了一个类的实例,但如果你可以创建自己的类焦化物或焦化等..类似于String类,或者你可以写的方式是什么列表或堆栈使用您自己的类使用矢量。 Here you go

所以,你可以在帖子的开头是这样

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); } 
     } 
};