我已经完成了这个C ++数据结构程序大部分是正确的,但我遇到了RefFunction()
参数的问题。它们设计得不是很合适。它们不应该通过价值传递,而是通过引用传递,我不知道该怎么做。它需要引用int
和对double
的引用。它查询用户输入要存储在其参数引用的变量中的值。然后能够返回类实例并在main()
中打印值。我非常感谢任何帮助,因为我很困难。非常感谢你。
标题文件:
#ifndef Prog1Class_h
#define Prog1Class_h
//A data structure of type Prog1Struct containing three variables
struct Prog1Struct
{
int m_iVal;
double m_dVal;
char m_sLine[81];
};
// A class, Prog1Class, containing a constructor and destructor
// and function prototypes
class Prog1Class
{
public:
Prog1Class();
~Prog1Class();
void PtrFunction(int *, double *);
void RefFunction(int, double);
void StructFunction(Prog1Struct *);
};
#endif
.CPP文件
#include "Prog1Class.h"
#include <string>
#include <iostream>
using namespace std;
Prog1Class::Prog1Class() {}
Prog1Class::~Prog1Class() {}
// PtrFunction shall query the user to input values to be stored in the
// variables referenced by it's pointer arguments
void Prog1Class::PtrFunction(int *a, double *b)
{
cout << "Input keyboard values of type integer and double"<<endl;
cin>>*a >>*b;
}
// RefFunction shall be a C++ Reference function and shall query the user to
// input values to be stored in the variables referenced by it's arguments
void Prog1Class::RefFunction(int a, double b)
{
cout << "Input keyboard values of type integer and double"<<endl;
cin >>a >>b;
}
// StructFunction shall query the user to input values to be stored in the
// three fields of the data structure referenced by its argument
void Prog1Class::StructFunction(Prog1Struct* s)
{
cout << "Input keyboard values of type integer and double"<<endl;
cin >>s->m_iVal>>s->m_dVal;
cout <<"Input a character string";
cin.ignore(1000, '\n');
cin.getline(s->m_sLine, 81, '\n');
}
答案 0 :(得分:2)
在C ++中,您不需要使用指针来通过引用传递。
声明这样的函数:
void Prog1Class::RefFunction(int& a, double& b)
您对RefFunction
内的a和b所做的更改将反映在原始变量