我正在尝试提示用户键入数据然后调出该函数以打印出来自“类”函数的数据...这是我下面的代码,它返回了奇怪的数字。
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <string>
using namespace std;
class planet
{
public:
int id_planet;
float x,y,z;
};
void report_planet_properties(planet P)
{
cout<<"Planet's ID: "<<P.id_planet<<endl;
cout<<"Planet's coordinates (x,y,z): ("<<P.x<<","<<P.y<<","<<P.z<<")"<<endl;
}
void set_planet_properties(planet Q)
{
cout<<"Enter planet's ID: ";
cin>>Q.id_planet;
cout<<"Enter planet's coordinates (x,y,z): ";
cin>>Q.x>>Q.y>>Q.z;
}
int main()
{
planet G;
set_planet_properties(G);
report_planet_properties(G);
}
答案 0 :(得分:4)
这非常简单:您通过值而不是引用传递。这意味着您的函数会收到您传递的对象的副本,而不是对象本身。这对report_planet_properties()
来说不是一个大问题,因为它不会改变收到的对象的值(虽然你正在做一个不必要的复制),但是set_planet_properties()
只会改变收到的副本的值,不是原始对象。
修复非常简单。只需以这种方式声明您的功能:
void report_planet_properties(const planet& P) // Pass a reference that will not be modified
void set_planet_properties(planet& Q) // Pass a reference that may be modified
如果您不知道什么是引用,则需要阅读基本的C ++书籍。基本上,正如我之前所说,这是传递对象而不是对象副本的机制。
答案 1 :(得分:1)
此函数按值接受对象行星:
void set_planet_properties(planet Q)
所以当你拨打这个电话时:
set_planet_properties(G);
当创建一个名为本地副本的对象的函数时,您可以修改该副本的字段,并在函数终止时该副本消失。如此简单的解决方案是通过指针或引用传递对象:
void set_planet_properties(planet &Q) // reference
void set_planet_properties(planet *Q) // pointer
在这种情况下,是优选的。
但更好的解决方案是让report_planet_properties
和set_planet_properties
成为类方法。
答案 2 :(得分:0)
由于您将按值传递给方法set_planet_properties(planet Q)
和report_planet_properties(planet P)
,因此每个方法都有自己的Planet
对象副本,该副本仅对该方法是本地的。因此,对该副本所做的更改在该方法之外不可见。
您可以将指针传递给对象这些方法,如
void report_planet_properties(planet *P);
void set_planet_properties(planet *Q);
并在main
方法中传递对象的地址。
set_planet_properties(&G);
report_planet_properties(&G);
这使得两个方法都传递相同的对象,因此对这个对象的修改在这些方法之外也是可见。
答案 3 :(得分:0)
其他答案非常完整。这是另一种解决方案:
class planet{
public:
int id_planet;
float x,y,z;
planet() : id_planet(0),x(0),y(0),z(0) {}
};
planet set_planet_properties(planet Q)
{
cout<<"Enter planet's ID: ";
cin>>Q.id_planet;
cout<<"Enter planet's coordinates (x,y,z): ";
cin>>Q.x>>Q.y>>Q.z;
return Q;
}
void main()
{
planet G;
G = set_planet_properties(G);
report_planet_properties(G);
}
您也可以通过您的函数返回该对象。