[英]Value doesn't change
// Example program
#include <iostream>
#include <string>
using namespace std;
class circle {
private:
double r;
double const pi=3.14;
public:
circle(double rad){
r=rad;
}
void periArea(){
double p,s;
p=2*pi*r;
s=pi*pi*r;
cout<<"\nS= "<<s<<endl;
cout<<"\nP= "<<p<<endl;
}
friend void changeRad(circle circle, double newrad);
};
void changeRad(circle circle, double newrad){
circle.r=newrad;
}
int main()
{
double inpr,newr;
cout<<"input radius: ";
cin>>inpr;
circle c1(inpr);
c1.periArea();
cout<<"\ninput new radius: ";
cin>>newr;
changeRad(c1,newr);
c1.periArea();
}
I've got this cpp code that has to define a class circle that calculates perimeter and area then using a friend function change the radius and calculate the area and perimeter again. 我已经获得了这个cpp代码,该代码必须定义一个类圆,该类圆计算周长和面积,然后使用一个朋友函数更改半径并再次计算面积和周长。 However I get the same p and s values even after the change function.
但是,即使在更改函数之后,我也会得到相同的p和s值。
Crudely, you need to change your function to pass the circle by reference : 粗略地讲,您需要更改函数以通过引用传递圆:
void changeRad(circle& circle, double newrad){
(Note the use of &
). (请注意
&
的使用)。 Otherwise a copy of the circle
instance is passed to the function and any changes to that copy will not be reflected in the original. 否则,将把
circle
实例的副本传递给函数,并且对该副本的任何更改都不会反映在原始实例中。
But , the normal way of doing things is to arrange your code so that you use 但是 , 通常的处理方式是安排代码,以便您使用
c1.changeRad(newr);
at the call site. 在呼叫站点。
Also, your use of a double
to store pi to just 3 significant figures is pretty terrible. 另外,使用
double
来将pi存储到仅3个有效数字非常糟糕。 My favourite way is to use 我最喜欢的方式是使用
const double PI = std::atan(1.0) * 4;
since the C++ standard does not define pi for you ( M_PI
is POSIX, not ISO!). 因为C ++标准并不为你定义PI(
M_PI
是POSIX,而不是ISO!)。
You have to pass an object the type Circle by reference 您必须通过引用传递类型为Circle的对象
friend void changeRad( circle &circle, double newrad);
^^^
Take into account that though it is a valid declaration of a parameter when its name coincides with the name of the type nevertheless this can confuse the reader and the name of the parameter hides the name of the type. 要注意的是,尽管它的名称与类型的名称重合时它是参数的有效声明,但是这可能会使读者感到困惑,并且参数的名称隐藏了该类型的名称。 So it is better to rename the name of the parameter as for example
因此,最好重命名参数名称,例如
friend void changeRad( circle &c, double newrad);
^^
Also it is better to make the function a non-static member of the class. 另外,最好使函数成为该类的非静态成员。 For example
例如
void changeRad( double newrad );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.