重载多个操作符
Overloading multiple operators
简单地说,我的目标是让foo[bar]返回type1,而foo[bar]=返回type2。
我正在用c++写一个对象,它进展得很好,但是有一件很小的事情我想做,但这似乎是不可能的。
我的对象是一个存储类,所以我使用数组下标来访问值。我还需要赋值,所以我也重载了=操作符。然而,这有点不方便,因为我的类保存的值是第一类对象,所以对于我的数组下标重载,我不能原样返回它们。我必须返回一个中间类来处理=操作符,但我也想在不额外键入的情况下检索值。
有什么办法可以做到吗?粗俗的方式是可以接受的
编辑:这里有一个例子,它(应该)做什么
#include<cstdio>
#include<cstdlib>
class foo{
char* a[100];
foo(){
for( int i = 0; i < 100; i ++)
a[i] = 0;
}
char* operator[] (int location){
return a[location];
}
foo& operator[]= (int location, const char* value ){
if( a[location] == 0 )
a[location] = (char*) malloc( strlen( value ) + 1 );
else
a[location] = (char*) realloc( a[location], strlen( value ) + 1 );
strcpy( a[location], value );
}
};
int main(){
foo bar;
bar[20] = "Hello";
printf( "bar[20] = %sn", bar[20] );
bar[20] = "Hello There";
printf( "bar[20] = %sn", bar[20] );
printf( "bar[20][0] = %cn", bar[20][0] );
}
Output:
bar[20] = Hello
bar[20] = Hello There
bar[20][0] = H
再次编辑:我想我会尝试用一种不同的,但可行的方式来表达。当类被引用时,是否有方法重载返回类型?如果我有
class foo{
bool a;
bool operator /*referenced*/ (){
return a
}
foo& operator=(bool b){
a = b;
}
};
int main(){
foo a;
a = b;
if( a == b )
printf("It Works!");
}
实际上可以工作吗?
没有operator[]=
,因此解决方案是编写具有两个关键功能的某种包装器类:operator=
接受值并将其设置为父容器,以及从父容器获取值并返回值的隐式转换操作符。然后,您的operator[]
将返回这样的包装。
class foo
{
friend class wrapper;
public:
class wrapper
{
friend class foo;
foo & _parent;
int _index;
wrapper(foo & parent, int index) : _index(index), _parent(parent) {}
public:
wrapper & operator=(const char * value)
{
if( _parent.a[_index] == 0 )
_parent.a[_index] = (char*) malloc( strlen( value ) + 1 );
else
_parent.a[_index] = (char*) realloc( _parent.a[_index], strlen( value ) + 1 );
strcpy( _parent.a[_index], value );
return *this;
}
operator char *()
{
return _parent.a[_index];
}
};
char* a[100];
foo()
{
for( int i = 0; i < 100; i ++)
a[i] = 0;
}
wrapper operator[] (int location){
return wrapper(*this, location);
}
};
对于第二个问题,您总是可以在foo
上重载operator==
。但也许我误解了。
如果您愿意使用c++(正如您的标签所建议的),那么大部分工作已经为您完成了:
class foo: public vector<string>
{
public:
foo()
{
resize(100);
}
};
int main()
{
foo bar;
bar[20] = "Hello";
cout << "bar[20] = " << bar[20] << endl;
bar[20] = "Hello There";
cout << "bar[20] = " << bar[20] << endl;
cout << "bar[20][0] = " << bar[20][0] << endl;
}