不完整类型无法定义

时间:2017-01-05 12:55:23

标签: c++ operator-keyword

Hello Guys我正在学习运算符重载和练习我正在编写代码来添加复数。

我似乎已经完成了所有的步骤,但在主要的时候我创建了我的班级的对象然后我说

  

E:\ Opp \ Practice \ ComplexNumbers \ main.cpp | 9 | error:aggregate'Complex   c2'类型不完整,无法定义|

     

E:\ Opp \ Practice \ ComplexNumbers \ main.cpp | 9 | error:变量'Complex c2'   有初始化程序但不完整的类型|

您可以查看我的代码

#include <iostream>

using namespace std;

class Complex;
int main()
{

    Complex c1(10,20),c2(30,40),c3;
    c3=c1+c2;
    c3.Display();

    return 0;
}

class Complex
{

public:
    Complex();
    Complex(int,int);
    void setReal(int );
    void setImaginary(int );
    int getReal();
    int getImaginary();
    Complex operator + (Complex );
    void Display();

private:
    int real , imaginary;
};

Complex::Complex()
{
    real = 0;
    imaginary =0;
}


Complex::Complex(int r , int i)
{

    real = r;
    imaginary =i;
}
Complex Complex:: operator +(Complex num1)
{

    Complex temp;
    temp.real = num1.real + real;
    temp.imaginary=num1.imaginary + imaginary;
    return temp;
}

void Complex :: Display()
{
    cout << "Real " << real << "Imaginary " << imaginary << endl;
}

int Complex ::getReal()
{
    return real;
}
int Complex ::getImaginary()
{
    return imaginary;
}

void Complex ::setReal( int r)
{
    real = r;
}

void Complex::setImaginary(int i)
{
    imaginary = i;
}

1 个答案:

答案 0 :(得分:1)

在宣布int main()课程后,您必须移动Complex。这里的前瞻声明还不够。

前向声明(class Complex;)只允许你操作指针和引用(它告诉编译器类存在但稍后会定义)。它不允许您创建对象(这是您的main函数尝试执行的操作...此代码必须在class Complex {...};语句之后编译。