如何解决为什么在没有值的情况下调用成员函数时它不会给出正确的结果
为什么当我调用 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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。