[英]How to pass the name of a member from a struct as an argument into a function using C++?
我已經用盡了耐心,試圖找到這個特定的問題。
我正在嘗試從結構到函數中輸入特定成員的名稱。
我首先想到的是這是不可能的,因為函數的參數需要是在RAM中聲明和定義的變量。 但是,計算機能夠根據給定成員名稱的每個實例來解釋“成員”的位置。
以下是一個任意程序,其中我創建了一個結構數組,該程序將針對數組中的每個實例如何輸入結構中每個成員的所有數據。 然后它將嘗試顯示數組中特定成員的所有內容。 它不完整,因為我不知道如何使其工作。
#include theUsual
// global variables
const int SIZE = 10;
// structures
struct structureExample
{
dataType member1;
dataType member2;
...
};
// functions
void inputData(structureExample s[], int size);
void displayMember( dataType member, structureExample s[], int size);
int main
{
structureExample sE[SIZE];
dataType memberName = member1 // member1 from the declared struct structureExample
inputData(sE,SIZE);
displayMember(memberName, sE, SIZE);
system("PAUSE");
return 0;
}
// inputs all the data for all members in an array of structure examples
void inputData(structureExample s[], int size)
{
...
}
// display's all of the content of a particular member from an array
void displayMember( dataType member, structureExample s[], int size)
{
for (int i = 0; i<size; i++)
{
cout << s[i].member << endl;
}
}
因此,給定從structureExample到displayMember的任何成員名稱,它將為數組中的每個單元顯示該成員的所有內容。
我對此有很多疑問,但最大的兩個是,這還可以嗎? 如果可以,我該如何進行這項工作? 例子將不勝感激。
提前致謝!
看來您要在成員上使用指針:
struct structureExample
{
int member1;
float member2;
};
template<typename M>
void displayMember(M structureExample::*member, structureExample s[], int size)
{
for (int i = 0; i < size; i++)
{
std::cout << s[i].*member << std::endl;
}
}
int main()
{
structureExample sE[SIZE];
auto member = &structureExample::member1;
inputData(sE,SIZE);
displayMember(member, sE, SIZE);
}
變量名,參數名,成員名在編譯過程中全部丟失,它們被轉換為內存地址偏移量。 運行時沒有實際名稱。
您要的內容在C ++中是不可能的。 如果需要通過運行時確定的名稱訪問值,則必須實現自己的查找邏輯,例如使用std::map
,例如:
#include theUsual
#include <map>
#include <string>
// global variables
const int SIZE = 10;
// structures
struct structureExample
{
std::map<std::string, dataType> values;
};
// functions
void inputData(structureExample s[], int size);
void displayMember(const std:string &valueName, structureExample s[], int size);
int main
{
structureExample sE[SIZE];
inputData(sE, SIZE);
displayMember("valueName", sE, SIZE);
system("PAUSE");
return 0;
}
// inputs all the data for all members in an array of structure examples
void inputData(structureExample s[], int size)
{
for (int i = 0; i < size; ++i)
{
...
s[i].values["valueName"] = ...;
...
}
}
// display's all of the content of a particular member from an array
void displayMember(const std::string &valueName, structureExample s[], int size)
{
for (int i = 0; i < size; ++i)
{
std::cout << s[i].values[valueName] << std::endl;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.