struct A {
int i;
};
struct B {
A a;
operator A*() { return &a; }
};
int main(int argc, char *argv[])
{
B b;
return b->i;
}
Run Code Online (Sandbox Code Playgroud)
g++ 报告 error: base operand of ‘->’ has non-pointer type ‘B’
为什么?我已经想出如何绕过这个问题(使用operator->),但我不明白为什么不进行隐式转换.
我对以下代码感到困惑,它(对我来说令人惊讶)编译:
class A {
int a=0;
};
A returnsA(void)
{
static A myA;
return myA;
}
void works(void)
{
A anotherA;
returnsA() = anotherA;
}
Run Code Online (Sandbox Code Playgroud)
我在标准或网络上找不到任何表明它不应该编译的内容。对我来说,这似乎很奇怪。
我猜想returnsA()返回一个对象( 的副本myA),因此我们对其调用默认的复制赋值运算符,anotherA将其复制分配给返回的对象,然后该对象超出范围并被销毁。
我期待的行为更像这样,但无法编译:
int returnsint(void)
{
static int i=0;
return i;
}
void doesntwork(void)
{
int anotherint=0;
returnsint() = anotherint;
}
Run Code Online (Sandbox Code Playgroud)
有人可以进一步启发我了解这种行为吗?