![](/img/trans.png)
[英]How can I access the members of a subclass from a superclass with a different constructor?
[英]Can I call the subclass constructor from my superclass?
我想知道是否可以通过超类的重载运算符返回子类对象。
#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运算符&&(Specification&other){^
main.cpp:21:45:错误:无效使用不完整类型'struct AndSpecification'返回AndSpecification(* this,other);
在完全定义类之前,不能以这种方式使用不完整的前向类声明。 在某些情况下可以使用不完整的(转发)类声明,但这不是其中一种。
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
方法的替代方法,将运算符方法的定义放入一个转换单元中。
每当编译器必须知道类型的大小时,都必须对其进行定义。 声明不足以构造类型。
在您的情况下,简单的解决方法是使operator &&为自由函数并将其移至底部:
AndSpecification operator&& (Specification & left, Specification & right){
return AndSpecification(left, r)ight;
}
在我看来,自由二进制运算符要好于成员函数。
在完成对函数中使用的类之一的定义之前,您已经实现了内联函数定义。 编译器知道存在一个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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.