0

我已经完成了这个 C++ 数据结构程序大部分是正确的,但是我遇到了RefFunction()参数问题。它们的设计不太恰当。它们不应该通过值传递,而是通过引用传递,我不知道该怎么做。它需要对 a 的引用int和对 a 的引用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'); 
}
4

1 回答 1

2

在 C++ 中,您不需要使用指针来通过引用传递。

像这样声明函数:

void Prog1Class::RefFunction(int& a, double& b)

你对里面的a和b所做的改变RefFunction会反映在原来的变量中

于 2013-10-15T14:16:38.100 回答