简体   繁体   English

如何将变量从main传递到类下的函数?

[英]How to pass variables from main to a function under class?

Hey I have written a code using C++. 嘿,我已经使用C ++编写了代码。 The program is about calculating distance between two points of a plane. 该程序是关于计算平面两点之间的距离。 Without using class the program works fine but whenever I do it with class & wanna return a value it doesn't return any value. 如果不使用类,则程序可以正常工作,但是每当我对类进行操作并想返回一个值时,它都不会返回任何值。

` `

#include<iostream>
#include<math.h>
using namespace std;
class plane{
public:
    void getdata(float X1,float X2,float Y1,float Y2)
    {
        cout<< "Enter point X1 ";
        cin>>X1;
        cout<< "Enter point Y1 ";
        cin>>Y1;
        cout<< "Enter point X2 ";
        cin>>X2;
        cout<< "Enter point Y2 ";
        cin>>Y2;
    }
    double distance2(float A1,float A2,float B1,float B2)
{
    double distance;
    float side1,side2;
    side1=(A1-A2)*(A1-A2);
    side2=(B1-B2)*(B1-B2);
    distance=sqrt(side1+side2);
    return distance;
}
};

int main()
{
    float X1,X2,Y1,Y2;
    plane plane1,plane2;
    plane1.getdata(X1,X2,Y1,Y2);
    plane1.distance2(X1,X2,Y1,Y2);
    cout<<endl;
    plane2.getdata(X1,X2,Y1,Y2);
    plane2.distance2(X1,X2,Y1,Y2);
}

There are two errors in your code. 您的代码中有两个错误。

First one: you are not looking at the value returned from the method distance2 . 第一个:您没有查看方法distance2返回的值。 You should do: 你应该做:

 float distance=plane1.distance2(X1,X2,Y1,Y2);
 cout<<distance<<'\n';

Second one: you are not really initialising the variables float X1,X2,Y1,Y2; 第二个:您并没有真正初始化变量float X1,X2,Y1,Y2; declared in your main. 在您的主体中声明。 Read about passing arguments by value or by reference . 了解有关通过值或引用传递参数的信息

So, you should modify you method getdata to: 因此,您应该将方法getdata修改为:

void getdata(float &X1,float &X2,float &Y1,float &Y2)
{
    cout<< "Enter point X1 ";
    cin>>X1;
    cout<< "Enter point Y1 ";
    cin>>Y1;
    cout<< "Enter point X2 ";
    cin>>X2;
    cout<< "Enter point Y2 ";
    cin>>Y2;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM