如何使用C++将结构中的成员名称作为参数传递到函数中

How to pass the name of a member from a struct as an argument into a function using C++?

本文关键字:参数传递 函数 成员 C++ 何使用 结构      更新时间:2023-10-16

为了找到这个特殊的问题,我已经耗尽了耐心。

我正试图将结构中某个特定成员的名称输入到函数中。

我的第一个想法是,这是不可能的,因为函数的参数需要是在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;
    }
}