我可以从我的超类中调用子类构造函数吗?

时间:2019-07-14 12:44:08

标签: c++ oop

我想知道是否可以通过超类的重载运算符返回子类对象。

#include <stdio.h>
#include <iostream>
using namespace std;

struct AndSpecification;

struct Specification{
    virtual bool is_satisfied(int i) = 0;  



    AndSpecification operator&& (Specification & other){
        return AndSpecification(*this, other);
    }

};


struct Specification1 : Specification{
    int k;
    Specification1(int k) : k(k){}

    bool is_satisfied(int i){
        if (i > k)
            return true;
        return false;
    }

};

struct Specification2 : Specification{
    int k;
    Specification2(int k) : k(k){}

    bool is_satisfied(int i){
        if (i < k)
            return true;
        return false;
    }
};

struct AndSpecification : Specification{
    Specification& first;
    Specification& second;

    AndSpecification(Specification& first, Specification& second) : first(first), second(second){}

    bool is_satisfied(int i) override{
        return first.is_satisfied(i) && second.is_satisfied(i);
    }
};

我认为结果是我无法使用子类的构造函数,因为尚未定义它。错误消息是:

main.cpp:在成员函数“ AndSpecification Specification :: operator &&(Specification&)”中:

main.cpp:20:56:错误:返回类型“ struct AndSpecification”不完整      AndSpecification运算符&&(规范和其他){                                                         ^

main.cpp:21:45:错误:无效使用了不完整的类型“ struct AndSpecification”          返回AndSpecification(* this,other);

3 个答案:

答案 0 :(得分:0)

在完全定义类之前,不能以这种方式使用您不完整的正向类声明。在某些情况下可以使用不完整的(正向)类声明,但这不是其中一种。

C ++编译器从头到尾依次读取源代码。当看到您的操作员时,不知道这个神秘的类是什么,它正在返回。尚未定义。稍后才在头文件/源文件中对其进行定义。

您需要声明类方法,然后仅在返回的类完全定义后才定义它:

// ...

struct Specification{
    virtual bool is_satisfied(int i) = 0;  



    AndSpecification operator&& (Specification & other);

};

// After AndSpecification is declared, later:

inline AndSpecification Specification::operator&& (Specification & other){
    return AndSpecification(*this, other);
}

作为inline的替代方法,将运算符方法的定义放入转换单元之一。

答案 1 :(得分:0)

每当编译器必须知道类型的大小时,都必须对其进行定义。声明不足以构造类型。

对于您来说,简单的解决方法是使operator &&成为免费功能并将其移至底部:

AndSpecification operator&& (Specification & left, Specification & right){
        return AndSpecification(left, r)ight;
    }

在我看来,免费的二元运算符比成员函数要好。

答案 2 :(得分:0)

在完成在函数中使用的一个类的定义之前,您已经实现了内联函数定义。编译器知道有一个struct AndSpecification,但不知道您使用的特定构造函数存在。在类中声明您的方法,但是直到定义AndSpecification之后才定义它。

struct Specification{
    virtual bool is_satisfied(int i) = 0;  
    AndSpecification operator&& (Specification & other);
};

struct AndSpecification : Specification { ... }

inline Specification::operator&& (Specification & other) {
    return AndSpecification(*this, other);
}