结构中的 C++ 函数和通过引用调用值

标签 c++ function struct pass-by-reference

所有 - 我对此进行了相当多的研究。我的程序编译没有错误,但是结构中函数的值没有传递给程序。你能帮我弄清楚为什么他们不是吗?我包含了显示相关组件的代码片段。主要是,我的代码如下:“&allData::ConvertToC”没有从结构“allData”中的函数返回任何值。无论“allData.temperature”的输入如何,它只会返回值 1。我知道该程序的所有组件,除了提到的那些之外,都在工作。

代码片段:

//defining the struct

struct allData {
    char selection; 
    double centigrade; 
    double fahrenheit; 
    double temperature; 
    double ConvertToC (const double& temperature);
    double ConvertToF (const double& temperature);
} allData;

//adding data to the struct for the functions within the struct to use

cout << "Enter C for converting your temperature to Celsius, or enter F for converting your temperature to Fahrenheit, and press ENTER." << endl << endl;

cin >> allData.selection; 

cout << "Enter your starting temperature to two decimal places, and press ENTER." << endl << endl; 

cin >> allData.temperature; 

switch (allData.selection) {

//my attempt to reference the functions within the struct and the data in the struct, but it is not working and always returns a value of 1. 

case 'c': { &allData::ConvertToC; 

    cout << "Your temperature converted to Celsius is: " << &allData::ConvertToC   
    << endl << endl; 
    break; 
    }

case 'C': { &allData::ConvertToC; 

    cout << "Your temperature converted to Celsius is: " << &allData::ConvertToC    
    << endl << endl; 
    }
}


//Function definitions that are located in the struct. Do I define the functions in the normal way, like this, if they are located in the struct?

double allData::ConvertToF (const double& temperature) {

    double fahrenheit = 0;
    fahrenheit = temperature * 9 / 5 + 32;
    return fahrenheit; 

}


double allData::ConvertToC (const double& temperature) {

    double centigrade = 0;
    centigrade = (temperature - 32) * 5 /9; 
    return centigrade; 

}

最佳答案

您没有执行函数调用,您只是将函数指针传递给 cout 流。

我想你真正想要的是这样的:

 cout << "Your temperature converted to Celsius is: " << allData.ConvertToC(allData.temperature) << endl; 

此外,您不需要在“ConvertToC”方法中通过引用传递,因为您实际上并没有保存任何东西(“double”是 8 字节宽,而引用/指针在 32 位系统上是 4 字节,或 64 位系统上的 8 个字节)。

关于结构中的 C++ 函数和通过引用调用值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37993562/

相关文章:

c++ - 我的任务是将 lwIP 从 C 转换为 C++

c - 数组中最长的一系列元素

javascript - 在 JavaScript 中构建基本计算器 - 第一次工作但在循环中我收到 "___ is not a function"错误

golang 在两个 goroutine 之间同时传递结构

objective-c - 将 C 与 Objective C 混合

c++ - 从 HCURSOR 获取游标类型

C++ 使用指针合并文本

MySQL 函数返回要在查询中使用的表名称

c++ - 如何将 unordered_set 与自定义结构一起使用?

c++ - 使用boost解析xml