0
Why am I getting no output?
#include <iostream> using namespace std; class Car{ private: int horsepowers; public: void setHorsepowers(int x) { x = horsepowers; if(horsepowers>800){ cout<<"Too much"<<endl; } } int getHorsepowers() { return horsepowers; } }; int main() { int horsepowers; cin >> horsepowers; Car car; car.setHorsepowers(horsepowers); cout << car.getHorsepowers(); return 0; }
6 Respuestas
+ 2
Yes, that's right. You are calling the setter function with the VALUE in the x variable. And then this VALUE will be stored in horsepowers:
Variable <- Value
horsepowers = x
+ 4
😮 Hmm, that's lesson one for variables.
This is a normal value assigment to a variable. This works only in one direction:
Variable <- new value
If both directions should be possible, how do the compiler should know, what direction do you want in this case?
Maybe you can look at it like this:
FIRST open a container,
THEN put in the items.
+ 3
void setHorsepowers(int x) {
horsepowers = x;
+ 1
Use:
horsepowers = x;
instead of
x = horsepowers;
void setHorsepowers(int x) {
horsepowers = x;
if(horsepowers>800){
+ 1
SoloProg Coding Cat mind telling the difference between horsepowers = x and x = horsepowers?
Really curious on how the compiler understands one and not the other.
+ 1
So in this case Variable is horsepowers and the parameter is X which is going to be the argument when called later by the function, am I right?
I was first confused because both aren't numbers,hence both are variables. Guess I was wrong there.