This code asks the user to input the reistance and voltage and calculates current and power - i'm learning friend function but i can't understand them. Could someone please explain them and tell me how i could apply them to this code? Thanks.
When you declare a function (or another class) to be a friend of your class, you effectively allow it to access your private members as if they were public to it. Code Example:
I removed the arguments from the current and power functions (was such an idiot to put them there in the first place) - now I have another problem: when circuit calls the current function it manages to calculate the current - but this value of current doesnt get passed to Power so Power always comes out to be zero - how do I sort this out?
I'm dreadfully sorry - but i'm really quite bad at this classes stuff.
Mmmm... How do your functions look like? Like this?
1 2 3 4 5 6 7 8 9 10 11 12 13 14
//-----------implementation----------//
void Ohm::current()
{
double I=V/R;
std::cout<<"The current is: ";
std::cout<<I<<"\n";
}
void Ohm::power()
{
double P=I*V;
std::cout<<"The power is: ";
std::cout<<P<<"\n";
}
If yes, you still have a problem. You see, that I in your current function is not the member variable I. You create a new, temporary variable here. A partial solution would be to remove the double keyword from the above piece of code (from both current and power function). I'm saying partial because then you would also have a problem if you wanted to calculate first the power and then the current (because in calculating the power you use the current). A better way would be to calculate these values when you create your object (in the constructor) and just print the values in your current and power functions. Example: