gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:37:08 25 4
gpt4 key购买 nike

所有 - 我对此进行了相当多的研究。我的程序编译没有错误,但是结构中函数的值没有传递给程序。你能帮我弄清楚为什么他们不是吗?我包含了显示相关组件的代码片段。主要是,我的代码如下:“&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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com