【问题标题】:C++ Data Structures Programming: Passing Values by Reference? [duplicate]C++ 数据结构编程:通过引用传递值? [复制]
【发布时间】:2013-10-23 09:21:09
【问题描述】:

我已经完成了这个 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'); 
}

【问题讨论】:

  • 请避免使用指针:在您的情况下,它只是 void fn(int&, double&)。
  • 按值传递还不错,但是更改并没有传递给调用者:'void Prog1Class::RefFunction(int a, double b)'

标签: c++ function class pass-by-reference


【解决方案1】:

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

像这样声明函数:

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

您对RefFunction 中的a 和b 所做的更改将反映在原始变量中

【讨论】:

  • 非常感谢,程序现在可以正常编译运行了。
  • "在 C++ 中,您不需要使用指针通过引用传递。"我会说你永远不会“使用指针通过引用传递”。使用指针是按值传递。
猜你喜欢
  • 2015-11-14
  • 2013-05-12
  • 2011-02-02
  • 1970-01-01
  • 1970-01-01
  • 2012-01-04
  • 2018-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多