开发者

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

开发者 https://www.devze.com 2023-04-03 12:37 出处:网络
开发者_Go百科 It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. F
开发者_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

精彩评论

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