g++ error: field has incomplete type

g++ error: field has incomplete type

我正在尝试使用内部 classes。我需要从嵌套 class 调用 get 函数。我究竟做错了什么?感谢您的宝贵时间!

   class Discriminant
{
private:
    float d;
public:
    void calcDiscr(int temp_a,int temp_b,int temp_c)
    {
        d = (temp_b^2)-4*temp_a*temp_c;
    }
    float get_d()
    {
        return d;
    }
    class Result
    {
    private:
        float x1,x2;
    public:
        Discriminant tempObject1;//here comes the error
        void calcResult(int temp_a,int temp_b,int temp_c)
        {
            cout<<"object's d = "<<tempObject1.get_d();
            x1 = (-temp_b+sqrt(tempObject1.get_d()))/2*temp_a;
            x2 = (-temp_b-sqrt(tempObject1.get_d()))/2*temp_a;
        }
        void displayResult()
        {
            cout<<endl<<"x1 = "<<x1;
            cout<<endl<<"x2 = "<<x2;
        }
    };
};

当编译器读取

Discriminant tempObject1;//here comes the error

行,Discriminant 的定义尚未完全解析(因此出现 incomplete type 错误);仅以最后的 ; 结尾,关闭 class Discriminant 语句。

不需要 Discriminant 是完全定义类型的理论解决方案是使 tempObject1 要么:

  1. Discriminant*
  2. Discriminant&

其中只有方案一可行。

这是你的代码,无法编译:

class Discriminant
{
    // etc.

    class Result
    {
        // etc.
        Discriminant tempObject1; //here comes the error
    };
};

问题是,正如 haavee 所报告的那样,当您尝试使其成为 Result 的成员时,判别式未被完全解析(因此不完整)。

一个解决方案是使 tempObject1 成为指针,而不是值。

另一种解决方案是在判别式之后定义结果(我假设您想保留恕我直言,糟糕的内部 class 风格)。代码变为:

class Discriminant
{
    // etc.

    class Result;
};

class Discriminant::Result
{
    // etc.
    Discriminant tempObject1; // No error!
};

这应该可以解决您的编译问题。

P.S.: 我错过了你问题的第一部分:

I'm trying to work with inner classes. I need to call get function from the nested class.

我希望您使用嵌套 classes 不是试图使用 Java 的奇怪版本。

如果您希望您的内部 class 与外部 class 有一个 pointer/reference,就像 Java 中那样,您会失望的。这是一个 Java 的特点。 C++ 和 C# 没有实现这个奇怪的功能。您必须手动传递指针。