![](/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.