假设我有一堂课:
class foo
{
....
//some constructors here set val=34
....
private:
int val;
int & foo::operator,()
{
return val;
}
};
我希望能够将其用作:
foo bar;
printf(" %d ", bar); //i need to get value of bar.val
//with just using bar itself with
//using an overloading
//but , overloading does not work
//i need to get 34 without using bar.val
//i need this without any getter
//i need val to be private
问题:这种超载可能吗?如果是,如何?
我试过:
int foo::operator int()
{
return val;
}
但它说“可能未在转换函数上指定返回类型”:(
我试过:
operator int() const { return val; }
转换仅在 printf 和 cout 之外有效。
int e=foo;
printf(" %d ",e); //works