为什么在没有值的情况下调用成员函数时它不会给出正确的结果

问题描述

为什么当我调用 gett 函数并尝试打印输出时我的代码不起作用(第二个代码) 当我从 main(第一个代码)传递参数时,它会给出正确的输出。我首先使用 rs.power(arguments) 调用我的函数,然后使用我正在获取的 get 函数调用我的函数 - 第二个代码中的输出

代码 1

#include<iostream>
#include<cmath>
using namespace std;
class powm
{
public:
double result;

public:
inline power(double m,double n)
{
    result=pow(m,n);     
}
void display()
{
    cout<<result;
}
}rs;
int main()
{
    double a,b;
    cout<<"We are calculating the power of the number "<<endl;
    cout<<"Enter the number :"<<endl;
    cin>>a;
    cout<<"enter the power :"<<endl;
    cin>>b;
    rs.power(a,b);
    rs.display();
    return 0;
}

代码 2

#include<iostream>
#include<cmath>
using namespace std;
class powm
{
public:
double result,a,b;

public:
void gett()
{   
    cout<<"We are calculating the power of the number "<<endl;
    cout<<"Enter the number :"<<endl;
    cin>>a;
    cout<<"enter the power :"<<endl;
    cin>>b;
}
inline power()
{
    result=pow(a,b);     
}
void display()
{
    cout<<result;
}
}rs;
int main()
{
    
    rs.gett();
    rs.display();
    return 0;
}

解决方法

在第二个代码块中,您没有做任何事情来计算 result

试试

rs.gett();
rs.power();
rs.display();

我建议使用:

#include <iostream>
#include <cmath>

using namespace std;

class powm
{
   public:
      double result;

   public:
      // Make sure constructor initializes the member variables appropriately.
      powm(double m,double n) : result(pow(m,n)) {}
};

// Separate display to a non-member function.
// Make it general and not hard coded to output to cout.
std::ostream& operator<<(std::ostream& out,powm const& p)
{
   return out << p.result;
}

int main()
{
   double a,b;
   cout<<"We are calculating the power of the number "<<endl;
   cout<<"Enter the number :"<<endl;
   cin>>a;
   cout<<"enter the power :"<<endl;
   cin>>b;

   // Construct object.
   powm rs(a,b);

   // Display to cout.
   cout << rs << ened;

   return 0;
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...