在C ++中将struct传递给函数

时间:2013-12-12 21:07:23

标签: c++ struct parameter-passing

#include <iostream>

using namespace std;

float distance(tocki *A, tocki *B);

int main()
{
    struct tocki{
        int x, y;
    };

    tocki A, B, C;

    cout << "x = ";
    cin >> A.x;
    cout << "y = ";
    cin >> A.y;

    cout << "x = ";
    cin >> B.x;
    cout << "y = ";
    cin >> B.y;

    cout << "x = ";
    cin >> C.x;
    cout << "y = ";
    cin >> C.y;

    cout << distance(&A, &B);

    return 0;
}

//distance between (x1,y1) i (x2,y2) e  d = sqrt((x2-x1)^2 - (y2-y1)^2);

float distance(tocki *A, tocki *B){
    return sqrt(pow(A.y - A.x, 2) - pow(B.y - B.x, 2));
}

我得到的错误是:

'tocki' was not declared in this scope
'A' was not declared in this scope
'tocki' was not declared in this scope
'B' was not declared in this scope

在这一行:

float distance(tocki *A, tocki *B);

那么,我到底做错了什么?我想传递一个struct to function并在main()程序中获取该函数的结果。

2 个答案:

答案 0 :(得分:6)

将toki结构置于主函数之外

答案 1 :(得分:1)

struct tocki应该在声明函数distance之前声明,因此编译器知道在检查参数类型时结构是否存在。此外,您应该使用A-> y ecc。 ,因为你已经传递了一个指向结构的指针。