开发者

Overloading (),[] operators in c++ [closed]

开发者_Go百科 It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

How would you overload the () and [] operators in c++? Justify with some code. Won't it affect the integrity of the programming language?


It can't affect integrity of the programming language simply because operator overloading can be performed for user-defined types only. It is impossible to overload operators for built-in types in C++. You cannot change the behavior of [] with data pointers (that covers the arrays as well). You cannot change the behavior of () with function pointers. In other words, core language features of C++ cannot be overloaded.


Here's an example:

class Test {
  const int size = 128;
  int data[size];
public:
  Test() { 
    // allocate memory for data, etc.
  }

  int& operator[](int index) {
    return data[index];
  }
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜