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

时间:2015-04-27 05:12:37

标签: c++ structure

我正在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:\n\n"
        << "A) Calculate the distance from a specified set of     coordinates.\n"
        << "B) Print out the information for all waypoints.\n\n"
        << "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;

我在distanceCalculator函数调用中遇到错误,在dataInfo.latitude和dataInfo.longitude上表示&#34;表达式必须具有类类型。&#34;

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

2 个答案:

答案 0 :(得分:1)

变量dataInfoProcessingData的数组。班级ProcessingData有一个成员latitude

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

如果你想传递一个数组,你有几个选择。传递数组很简单:

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);

答案 1 :(得分:1)

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

此处没有double的数组。看起来好像你试图通过从dataInfo中选择所有纬度双打来自动“查看”一个双精度数组,但它不会那样工作。

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

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