【问题标题】:Pass by reference and type casting problems in c++c++ 中的引用传递和类型转换问题
【发布时间】:2020-11-07 08:01:57
【问题描述】:

我正在学习 c++,但在这个程序中遇到了问题。 我要做的是编写一个函数,计算最大 2 个参数 x 和 y,每个参数类型为“对 const double 的引用”。该函数返回类型“对双精度的引用”。返回整个条件表达式,将其类型转换为 (double &) 以覆盖“const”变量。

所以我把这个函数写在一个名为“fmax.cpp”的文件中

double& fmax(const double &x, const double &y)
{
    return (x > y) ? x : y; //Need type casting here?
}

我尝试在另一个文件 main.cpp 中调用函数

include <iostream>
using namespace std;

double& fmax(const double &x, const double &y);

int main()
{
    const double &x; //should I put &x or x here?
    const double &y; //should I put &y or y here?

    cout << "enter 2 values" << '\n';
    cin >> x >> y; //should I put & or no & here?

    //Am I calling the function correctly?
    cout << fmax(double &x, double &y) << '\n';
    return 0;
}

请指教如何正确编写程序。

【问题讨论】:

  • 这段代码有很多错误,听起来你应该read a good book
  • 我可以建议获得a good C++ book 吗?几乎每一行都有注释都是错误的(包括你选择的函数名称与using namespace std;结合时)
  • 您已将变量声明为 const,那么您将无法在 cin 行中为其赋值。您还应该创建一个头文件并将其包含在 main.cpp 中。为什么要定义引用变量?不,你没有正确调用它。其他错误也很少。您可以遵循一些 cpp 教程,这将有助于理解这些概念。

标签: c++


【解决方案1】:

这个程序应该是这样的:

#include <iostream>

double fmax(double x, double y) {
    return x > y ? x : y;
}

int main()
{
    double x; 
    double y; 

    std::cout << "enter 2 values" << '\n';
    std::cin >> x >> y;

    const auto res = fmax(x, y);
    std::cout << res << '\n';
    return 0;
}

通过引用传递双精度(整数、浮点数和其他小类型)是没有用的,因为传递的内存地址的大小是平台指针的大小(32 位上为 4 个字节,64 位上为 8 个字节)。例如 int 的大小为 4 个字节。

我添加了 const 和 auto 作为示例。

【讨论】:

【解决方案2】:

代码有几个缺陷:

  1. 只存在一个函数签名,但没有定义或链接任何头文件。

  2. 你不需要使用:

    fmax(double &x, double &y)
    // __^^^^^^_____^^^^^^____ errors
    
  3. 引用时使用const限定符,通常在保证变量在代码中的任何地方都不会更改时使用。您无需在此处使用参考。

当程序要改变变量的值时,小心使用const。否则会产生错误。


代码重新定义:

fmax.h

double& fmax(const double &x, const double &y);

fmax.cpp

double& fmax(const double &x, const double &y) {
    return (x > y) ? x : y;
}

main.cpp

#include <iostream>
#include "fmax.h"

int main(void) {
    double x, y;

    std::cout << "Enter 2 values: ";
    std::cin >> x >> y;

    std::cout << fmax(x, y) << '\n';

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多