2017-08-04 49 views
5

在以下示例中,前向聲明struct Y前向聲明是不夠的。如果你註釋掉X :: b,它編譯得很好,因爲Y有一個完整的結構聲明可供使用,但X只有前向聲明。如何在需要提及需要循環聲明的其他類的類中初始化變量?

#include <functional> 
#include <iostream> 

struct Y; 

struct X 
{ 
    std::function<bool(Y&)> b{[] (auto& y_) { return y_.a; }}; 

    bool a{false}; 
}; 

struct Y 
{ 
    std::function<bool(X&)> b{[] (auto& x_) { return x_.a; }}; 

    bool a{true}; 
}; 

int main() 
{ 
    return 0; 
} 

Ideone

以下是修復我能想出:

#include <functional> 
#include <iostream> 

struct Y; 

struct X 
{ 
    X(); 
    std::function<bool(Y&)> b; 

    bool a{false}; 
}; 

struct Y 
{ 
    Y(); 
    std::function<bool(X&)> b{[] (auto& x_) { return x_.a; }}; 

    bool a{true}; 
}; 

X::X() : b([] (auto& y_) { return y_.a; }) {} 
Y::Y() : b([] (auto& x_) { return x_.a; }) {} 

int main() 
{ 
    return 0; 
} 

Ideone

雖然它在這個例子中,如果類呈多形性,這分別需要using X::X;using Y::Y;

有沒有辦法在頭文件本身做到這一點?

+2

爲什麼你會需要例如在孩子課中使用X :: X'?構造函數在類中仍然是*聲明的,它只是在類定義之外的* defined *(實現的)(即它不是內聯的)。 –

+0

是嗎?讓我試試吧 – kim366

+1

所有你需要的是[正確的頭文件/實現結構](https://stackoverflow.com/questions/625799/resolve-header-include-circular-dependencies)而不是初始化類體中的成員在構造函數初始化列表中執行。 – NathanOliver

回答

0

你可以這樣做:

#include <functional> 

template <typename T> bool (*get_lambda())(T&) {return [] (auto& y_) { return y_.a; };}; 

struct Y; 

struct X 
{ 
    std::function<bool(Y&)> b{get_lambda<Y>()}; 

    bool a{false}; 
}; 

struct Y 
{ 
    std::function<bool(X&)> b{get_lambda<X>()}; 

    bool a{true}; 
}; 

int main() 
{ 
    return 0; 
} 
+0

好吧,所以把定義放在一個公共函數中的單獨頭文件中。看起來很合理。 – kim366

相關問題