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];
}
};
精彩评论