C++:类型转换运算符重载 - Visual Studio 2013内部错误

Jam*_*mes 1 c++ typecasting-operator visual-studio-2013

我正在重载类型转换操作符,并在Visual Studio 2013中发生内部错误.

这是指数类的标题:

#pragma once
#include "Calc.h"
#include <iostream>

using namespace std;


class Exponent
{

private:
    int base;
    int exponent;
public:
    Exponent();
    Exponent(int a)
    {
        base = a;
    }

    int getBase()
    {
        return base;
    }


};

void printExp(Exponent e)
{
    cout << e.getBase() << endl;
}
Run Code Online (Sandbox Code Playgroud)

这是calc.h我写的将包含重载类型转换函数:

#pragma once
#include "Exponent.h"

class Calc
{
private:
    int acc;
public:
    Calc();
    Calc(int a);

    operator Exponent()  //this is where I get an error. 
    { 
        return Exponent(acc); 
    }


};
Run Code Online (Sandbox Code Playgroud)

这是主要功能:

#include "stdafx.h"
#include <iostream>
#include "Exponent.h"
#include "Calc.h" 

using namespace std;

int main()
{
    Calc c(6);

    printExp(c);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我不知道为什么我在这里收到错误:

operator Exponent()  //this is where I get an error. 
{ 
    return Exponent(acc); 
}
Run Code Online (Sandbox Code Playgroud)

这在某种程度上使Visual Studio崩溃,显示如下错误:

Microsoft(R) C\C++ Optimizing compiler has stopped working...
Run Code Online (Sandbox Code Playgroud)

Ada*_*eld 5

内部编译器错误(ICE)是编译器错误 - 运行良好的编译器应始终报告错误代码的合理错误.我建议您在connect.microsoft.com上提交错误报告.

但是,您的代码确实存在明显问题:您的两个头文件之间存在循环依赖关系.Exponent.h包括Calc.h,它又包含Exponent.h.即使编译器没有与ICE崩溃,它仍然会使用此代码报告错误(可能是"未定义符号"变种).

对这种情况有一个简单的解决方法 - 因为Exponent.h实际上没有对Calc.h的任何依赖,你只需#include "Calc.h"从Exponent.h中删除该行,循环依赖就会消失.