p****o 发帖数: 1340 | 1 i have a question on operators in c++.
/* header file */
class A;
class B
{
public:
operator A*();
double& operator [](unsigned int);
};
/* cpp file */
B b;
b[3] = 2.2;
the compiler will complain about the "b[3]=2.2" line b/c there are two
possible ways to interpret the code:
1. b.operator[](unsigned) -- my desired operation
2. b.operator A*.operator[] -- which is build-in.
the above code can be compiled and run well under linux, but now i am using
g++ under windows. i just realize suc |
p***o 发帖数: 1252 | 2 It's in 13.3, though I didn't read it ...
【在 p****o 的大作中提到】 : i have a question on operators in c++. : /* header file */ : class A; : class B : { : public: : operator A*(); : double& operator [](unsigned int); : }; : /* cpp file */
|
p****o 发帖数: 1340 | 3 yes, the strictness of the compiler can expose many un-imaginable problems
in the code. it actually takes me quite some time to figure out the error
message because the real code is much more complicated than the sample given.
【在 p***o 的大作中提到】 : It's in 13.3, though I didn't read it ...
|
p***o 发帖数: 1252 | 4 Oh, yes. But implementing operator T* for [] is strange enough.
given.
【在 p****o 的大作中提到】 : yes, the strictness of the compiler can expose many un-imaginable problems : in the code. it actually takes me quite some time to figure out the error : message because the real code is much more complicated than the sample given.
|
r*********r 发帖数: 3195 | 5 shouldn't g++ pick "operator []"? the other path requires more "effort". |
p****o 发帖数: 1340 | 6 in my code, T* is an abstract opaque pointer due to the system design.
while [] is an operator for accessing the real data. so they both make
sense somehow.
now the problem is solved. i declare the operator [] as
double& operator [] (int);
originally i used "unsigned int" for the most strict type checking. but in
practice, the compiler treated all constants like 5 as int but not unsigned.
so there is a conversion from int to unsigned. that's why the compiler does
not know which decoding path to
【在 p***o 的大作中提到】 : Oh, yes. But implementing operator T* for [] is strange enough. : : given.
|
i***h 发帖数: 12655 | 7 [] by default is pointer reference
I think this way is more elegant than overloading [].
[] overloading can be used for more complicated index operation.
【在 p***o 的大作中提到】 : Oh, yes. But implementing operator T* for [] is strange enough. : : given.
|