2017-08-21 48 views
1

我想將一個結構的成員變量與一個類相關聯。所以當我創建一個新的類時,我可以指定它在結構體中與這個成員變量關聯。例如:是否有可能傳遞一個結構的成員變量作爲參數

struct A { 
    int a; 
    int b; 
}; 

static A a[2]; 
a[0].a = 1; 
a[0].b = 2; 
a[1].a = 3; 
a[1].b = 4; 

class foo { 
public: 
    foo(int index, ???) { 
    c = a[index].???; //Is it possible to define the 2nd parameter as a getter of struct A's member? So this line could resolve to either a[index].a or a[index].b? 
    } 
private: 
    int c; 
}; 

這樣:

  • 新FOO(0,???)將集合C以1中給出???參考A :: a
  • 新foo(0,???)將c設置爲2給出???參考A :: b
  • 新富(1,???)將c設置爲3參考A :: a
  • 新富(1,???)將c設置爲4參考A :: b
+2

指向成員,也許?你的問題不是很清楚。 –

回答

4

是的,這是可能的,你需要傳遞的數據成員指針:

#include <iostream> 

struct A 
{ 
    int a; 
    int b; 
}; 

static A a[2] 
{ 
    1, 2 
, 3, 4 
}; 

class foo 
{ 
    public: int c; 

    public: 
    foo(int const index, int A::* const p_field) 
    { 
     c = a[index].*p_field; 
    } 
}; 

int main() 
{ 
    foo const f1(0, &A::a); 
    ::std::cout << f1.c << ::std::endl; 
    foo const f2(0, &A::b); 
    ::std::cout << f2.c << ::std::endl; 
    foo const f3(1, &A::a); 
    ::std::cout << f3.c << ::std::endl; 
    foo const f4(1, &A::b); 
    ::std::cout << f4.c << ::std::endl; 
    return 0; 
} 

Check this code at online compiler

+0

這正是我所期待的!謝謝 – Aaron

2

你有幾個選項。如果你只是想要整數(就像你在你的代碼中發佈的那樣),那麼只需要一個整數作爲參數給構造函數,並將它傳遞給正確的數字。

class foo { 
public: 
    foo(int val) { 
    c = val 
    } 
private: 
    int c; 
}; 

int main() { 
    foo f(a[0].b); 
} 

或者你可以採取一個整數的引用。這樣,如果一個改變,其他的意志爲好:

class foo { 
public: 
    foo(int &val) : c(val) { } //need to use an initialization list for this one 
private: 
    int &c; 
}; 

int main() { 
    foo f(a[0].b); 
    a[0].b = -1; //f.c will be -1 now as well 
} 
0

使用數據成員指針在VTT的答案是最直接的解決方案,但我經常發現成員指針和成員函數指針語法有點麻煩,我相信編譯器很難優化。

對於這些我喜歡使用無狀態lambda的東西。您可以將lambda函數傳遞給函數模板,然後編譯器可以輕鬆優化它:

#include <iostream> 

struct A { 
    int a; 
    int b; 
}; 

static A a[2]{{1, 2}, {3, 4}}; 

class foo { 
public: 
    int c; 
public: 
    template<typename F> 
    foo(int index, F getter) { c = getter(a[index]); } 
}; 

int main() { 
    auto agetter = [](const A& a){ return a.a; }; 
    auto bgetter = [](const A& a){ return a.b; }; 

    foo const f1(0, agetter); 
    std::cout << f1.c << "\n"; 
    foo const f2(0, bgetter); 
    std::cout << f2.c << "\n"; 
    foo const f3(1, agetter); 
    std::cout << f3.c << "\n"; 
    foo const f4(1, bgetter); 
    std::cout << f4.c << "\n"; 
} 
相關問題