不完整类型无法定义

Incomplete Type can not be Defined

大家好,我正在学习运算符重载,为了练习,我正在编写代码来添加复数。

我似乎已经正确完成了所有步骤,但主要是当我创建 Class 的对象时,我说

E:\Opp\Practice\ComplexNumbers\main.cpp|9|error: aggregate 'Complex c2' has incomplete type and cannot be defined|

E:\Opp\Practice\ComplexNumbers\main.cpp|9|error: variable 'Complex c2' has initializer but incomplete type|

你可以看看我的代码

#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;
}

您必须在 Complex class 声明后移动 int main()。前向声明在这里是不够的。

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