【问题标题】:Incomplete Type can not be Defined无法定义不完整类型
【发布时间】:2017-01-05 12:55:22
【问题描述】:

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

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

E:\Opp\Practice\ComplexNumbers\main.cpp|9|错误:聚合'复杂 c2' 类型不完整,无法定义|

E:\Opp\Practice\ComplexNumbers\main.cpp|9|错误:变量“复杂 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;
}

【问题讨论】:

    标签: c++ operator-keyword


    【解决方案1】:

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

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

    【讨论】:

    • 我想你在我编辑我的帖子之前写了这个评论来解释更多。现在的解释还不够吗?
    • 是的,谢谢,现在我明白了上帝保佑你:)
    • 是的,但我们必须等待 6 分钟
    猜你喜欢
    • 2012-01-08
    • 2012-03-06
    • 2014-05-20
    • 2021-06-24
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多