RDX*_*RDX -2 c++ constructor operator-overloading
有人可以解释下面的程序如何成为"AabAabAab .."的infinte循环.
#include "stdafx.h"
#include <iostream>
using namespace std;
class Base {
public:
Base(int j=1):i(j)
{cout<<"B";}
private:
int i;
};
class Case{
public:
Case(int j=1):i(j) {cout<<"A";}
operator Base() { cout<<"ab"; return *(new Case); }
private:
int i;
};
int main()
{
Base obj = Case();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Base obj = Case();
Run Code Online (Sandbox Code Playgroud)
这会调用Case默认构造函数print A.然后,Base通过此运算符进行转换,该运算符具有无限递归:
operator Base() { cout<<"ab"; return *(new Case); }
Run Code Online (Sandbox Code Playgroud)
因为它试图返回一个必须转换为的Case实例(打印abA),它Base调用转换操作符,它创建一个Case实例(打印abA),它必须转换为Base,...