全部 - 我对此进行了相当多的研究。我的程序编译没有错误,但结构中函数的值没有传递给程序。你能帮我弄清楚他们为什么不是吗?我包含了显示相关组件的代码片段。主要是,我的代码如:“& allData :: ConvertToC”没有从struct“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;
}
答案 0 :(得分:1)
您没有执行函数调用,只是将函数指针传递给cout流。
我认为你真正想要的是:
cout << "Your temperature converted to Celsius is: " << allData.ConvertToC(allData.temperature) << endl;
此外,您不需要在“ConvertToC”方法中通过引用传递,因为您实际上没有保存任何内容(“double”是8字节宽,并且引用/指针在32位系统上是4字节,或64位系统上的8个字节)。
答案 1 :(得分:0)
// Name of struct made distinct from its instance, for clarity.
struct AllData {
char selection;
double centigrade;
double fahrenheit;
double temperature;
double ConvertToC ();
double ConvertToF ();
} allData;
...
allData.selection = 'C';
allData.temperature = 74.5;
switch (allData.selection)
{
case 'c':
case 'C':
cout << "Your temperature converted to Celsius is: " << allData.ConvertToC() << endl << endl;
break;
}
...
double AllData::ConvertToF ()
{
//double fahrenheit = 0; Why not store the result in the struct?
fahrenheit = temperature * 9 / 5 + 32;
return fahrenheit;
}
double AllData::ConvertToC ()
{
//double centigrade = 0;
centigrade = (temperature - 32) * 5 / 9;
return centigrade;
}