Kas*_*lai 6 c++ operator-keyword
简而言之,我的目标是让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] = %s\n", bar[20] );
bar[20] = "Hello There";
printf( "bar[20] = %s\n", bar[20] );
printf( "bar[20][0] = %c\n", bar[20][0] );
}
Output:
bar[20] = Hello
bar[20] = Hello There
bar[20][0] = H
Run Code Online (Sandbox Code Playgroud)
再次编辑:我想我会尝试以另一种方式,但可行的方式来表达这一点.有没有办法在引用类时重载返回类型?如果我有这样的话
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!");
}
Run Code Online (Sandbox Code Playgroud)
那真的有用吗?
没有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);
}
};
Run Code Online (Sandbox Code Playgroud)
对于第二个问题,好了,你总是可以过载operator==上foo.但也许我误会了.
| 归档时间: |
|
| 查看次数: |
1144 次 |
| 最近记录: |