表达式必须具有类类型(使用结构数组作为函数参数)

Expression Must Have Class Type (Using a struct array as a function parameter)

本文关键字:数组 结构 函数 参数 类型 表达式      更新时间:2023-10-16

我正在Visual Studio Pro 2013中编写一个C++程序,在尝试在函数调用中使用结构数组作为参数时遇到错误。这是我的代码。

struct ProcessingData
{
    double latitude;
    double longitude;
};
double distanceCalculator(double dataLat[], double dataLong[], double inLat, double inLong)
{
    //some code in here
}
int main()
{
    char userChoice;
    double userLatitude;
    double userLongitude;
    ProcessingData dataInfo[834];
    cout << "Welcome!n"
        << "Please select which option you would like to run:nn"
        << "A) Calculate the distance from a specified set of     coordinates.n"
        << "B) Print out the information for all waypoints.nn"
        << "Please enter your selection now: ";
    cin >> userChoice;
    switch (userChoice)
    {
    case 'a':   //Menu option for distance calculation
    {
        getTheFile();    //other function that is being used
        cout << "Please enter the latitude for the coordinate you are using:  ";
        cin >> userLatitude;
        cout << "Please enter the longitude for the coordinate you are using: ";
        cin >> userLongitude;
        distanceCalculator(dataInfo.latitude[], dataInfo.longitude, userLatitude, userLongitude)
    }
        break;

我在 dataInfo.latitude 和 dataInfo.longitude 上的 distanceCalculator 函数调用中收到错误,上面写着"表达式必须具有类类型"。

为什么我会收到此错误以及如何解决它?

变量 dataInfo 是一个 ProcessingData 数组。类ProcessingData具有成员latitude

你似乎想要处理一个由dataInfo元素的latitude成员组成的数组,但这样的数组不存在。可以获取结构的成员,但不能使用相同的语法在一个步骤中从数组的所有元素中提取该成员。

如果要传递数组,则有几个选择。传递数组很容易:

void foo(int A[])
{
  ...
}
int A[8];
foo(A);

问题是该函数很难知道数组的大小,因此很容易越界。我们可以为数组的大小添加另一个参数:

void foo(int A[], unsigned int nA)
{
  ...
}
int A[8];
foo(A, 8);

或开始使用标准容器:

void foo(vector<int> A)
{
  ...
}
vector<int> A;
foo(A);

ProcessingData的每个实例都包含一个用于纬度的double和一个用于经度的double

这里没有double数组。似乎您正在尝试通过从中选择所有 Latitude 双精度数组来自动"查看"dataInfo ,但它不是那样工作的。

最简单的解决方案可能是将函数更改为:

double distanceCalculator(ProcessingData data[], double inLat, double inLong)
{
    // logic here using things like data[5].latitude
}