c++ - 不完整类型无法定义

标签 c++ operator-keyword

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

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

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 类之后移动int main()。前向声明在这里是不够的。

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

关于c++ - 不完整类型无法定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41485690/

相关文章:

c++ - OpenMP:每个线程都有一个完整的 'for' 循环

swift - 错误 : '...' is not a prefix unary operator

c++ - vector::push_back 与 vector::operator[]

c++ - 使用基类的运算符>>创建派生类

Angular 2 : what differences between comparison operators == and === in ngIf directive

c++ - 根据属性选择 fstream 或 cout

c++ - 反汇编一个简单的 C++ 程序

C++、switch case 和编译器

c++ - 在 Qt Creator 中使用 'Analyze Memory' 工具

gnuplot - gnuplot 中有 in prod() 运算符吗?