当我看到标签“C++”和“运算符重载”,我的心报警接通。
C++运算符重载是复杂的,一些运营商等“()”或“ - >”变得更加困难。
我建议,运算符重载,使得无论是全局函数或方法具有相同purpouse之前,测试它的工作原理,以及后来与运营商更换。
全球友元函数例如:
class c {
private:
int n[10];
public:
c();
~c();
// int operator()(int i) { return n[i]; }
// there is a friend global function, that when receives a "c" object,
// as a parameter, or declares a "c" object, as a local variable,
// this function, will have access to the "public" members of "c" objects,
// the "thisref" will be removed, when turned into a method
friend int c_subscript(c thisref, int i) ;
};
int c_subscript(c* thisref, int i)
{
return c->n[i];
}
int main()
{
c* objC() = new c();
// do something with "objcC"
int x = c_subscript(objC, 3);
// do something with "x"
return 0;
} // int main(...)
局部功能( “办法”),例如:
class c {
private:
int n[10];
public:
c();
~c();
// int operator()(int i) { return n[i]; }
int subscript(int i) ;
};
int c::subscript(int i)
{
return this.n[i];
}
int main()
{
c* objC() = new c();
// do something with "objcC"
int x = c->subscript(objC, 3);
// do something with "x"
return 0;
} // int main(...)
而且,最后使用重载操作:
class c {
private:
int n[10];
public:
c();
~c();
int subscript(int i) ;
int operator()(int i) { return this.subscript(i); }
};
int c::subscript(int i)
{
return this.n[i];
}
int main()
{
c* objC() = new c();
// do something with "objcC"
int x = c->subscript(3);
// do something with "x"
int x = c(3);
// do something with "x"
return 0;
} // int main(...)
注意,在最后一个例子,我保留了一个唯一标识符的方法。
干杯。
为什么摆在首位这么多球?这可能是更有建设性的固定编码风格,而不是担心为什么一个十分可怕的一段代码看起来...真的丑。 –