can anyone show me how to input a value into one of my classes and then output it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <cstdlib>

using namespace std;


class Temperature
{

public:
static Temperature Fahrenheit (double f);
static Temperature Celsius (double c);
static Temperature Kelvin (double k);
private:
Temperature (double temp);
double _temp;
};
Temperature::Temperature (double temp):_temp (temp) {}

Temperature Temperature::Fahrenheit (double f)
{
return Temperature ((f + 459.67) / 1.8);
}

Temperature Temperature::Celsius (double c)
{
return Temperature (c + 273.15);
}

Temperature Temperature::Kelvin (double k)
{
return Temperature (k);
}

int main()
{
  
int option;


cout<<"1. Input the temperate (degree and unit)"<<endl;
cout<<"2. Display the temperate as current unit"<<endl;
cout<<"3. Convert and display the temperate as Celsius"<<endl;
cout<<"4.Convert and display the temperate as Fahrenhe"<<endl;
cout<<"5. Convert and display the temperate as Kelvin"<<endl;
cout<<"0. Exit the program"<<endl;

//cin>>option;
//as these were functions they need to be out of main (which is a function, you cannot have two functions inside each other!


//}

return(0);
}
Your class is pretty useless right now. You do have private members, but not a single non-static method that could access them. Did you really understand this whole class thing?
1
2
3
4
5
6
7
8
9
10
11
12
13
public:
static Temperature* GetInstance(double t) 
{
if (m_pInstance == NULL)
{
m_pInstance = new Temperature(t);
return m_pInstance;
}
else
{
return m_pInstance;
}
}


1
2
private:
static Temperature * m_pInstance;


I don't know what exactly you want. But in this way, you could use Temperature *pt = Temprature::GetInstance(t) to get a pointer to a temperatue object.
Last edited on
The using of the constructor in your class is not usual, do you really want to create a new object in this way? You could do better.

And also I couldnt' see any link between the topic tile and the class definition. Do you really ask:
"can anyone show me how to input a value into one of my classes and then output an object of a same class? If yes, the questions itself is not usual. You can do it technically, but usually C++ doesn't do it in this way in my understanding.

b2ee
Last edited on
@b2ee
Declaring constructor as private is usually used to initialize one and only one object, as shown above. This technique is generally used in Singleton Pattern.

Thanks for the indication. In my code, the Singleton pattern is not implemented by this way. An obvious drawback of the private constructor is: others class will never get chance to inherit the class.

Topic archived. No new replies allowed.