Reputation: 11
I was doing the foundation of a class program and I was trying to modify the value of an object of the class: In the main.cc:
#include <iostream>
#include "ComputeInt.h"
main()
{ ComputeInt computation;
computation.real() = 5;
computation.operator=(Factorial(computation));
}
In the .h:
#include <iostream>
#ifndef ComputeInt_H
#define ComputeInt_H
class ComputeInt
{ public:
int real();
};
ComputeInt Factorial(const ComputeInt& computation);
#endif
In the .cc:
#include <iostream>
#include "ComputeInt.h"
ComputeInt Factorial(const ComputeInt& computation)
{ ComputeInt result = computation.real() +1;
return result;
}
I get an error that says expression must be a modifiable lvalue, and if I try to use make I get
conversion from ‘int’ to non-scalar type ‘ComputeInt’ requested
I don´t know why it doesn´t work, computation.real is a int and so it should be able to use +1.
Thanks in advance
Upvotes: 1
Views: 148
Reputation: 1
In your current program real
is a member function of the class ComputeInt
and not a data member. So you can solve this issue as shown below:
.h
#ifndef ComputeInt_H
#define ComputeInt_H
class ComputeInt
{ public:
int real;//removed () here. This means real is a data member now
};
ComputeInt Factorial(const ComputeInt& computation);
#endif
.cpp
#include "ComputeInt.h"
ComputeInt Factorial(const ComputeInt& computation)
{ ComputeInt result ; //create object of type ComputeInt
result.real= computation.real +1; //note result.real at the left hand side
return result;
}
main.cpp
#include "ComputeInt.h"
#include<iostream>
int main()
{ ComputeInt computation;
computation.real = 5;
ComputeInt computation2;
computation2.real = 10;
computation.operator=(Factorial(computation2));
std::cout<<computation.real;//this prints 11
}
The output of the program can be seen here.
Upvotes: 2
Reputation: 653
Method real() returns integer by value so if you do:
computation.real() = 5;
you try to assign value "5" to another value. It is not possible, similarly like you are not allowed to do:
3 = 5;
conversion from ‘int’ to non-scalar type ‘ComputeInt’ requested
There is no known conversion from int you created by real()+1
to ComputeInt (you don't have constructor and/or operator=)
Upvotes: 2
Reputation: 2000
int real()
is defined as a class method (function) that returns an int, not an int itself.
If you want to make it an int, make it int real
without the ()
.
Upvotes: 1