It is not difficult to convert this Java code to C++ because it does not use advanced Java syntax or libraries. Just replace the all
public
and
private
keyword with
public:
and
private:
and also replace
this.num1
with
this->num1
and also replace
String
with
std::string
. Add a semi-colon at the end of the OP class (from
}
to
};
)
C++
main()
does not need to be in a class because C++ is not strictly OOP, so I remove the
TestOP
class
Inside
main()
, replace
system.out.println
code with
std::cout
. Do not need to instantiate OP object on the heap with
new
keyword. Just on the stack will do fine.
#include <iostream>
#include <string>
class OP
{
private:
float num1;
public:
OP(float num1) { this->num1 = num1; }
float getNum1() {
return num1;
}
void setNum1(float num1) {
this->num1 = num1;
}
std::string print() {
return std::string("num1= ") + std::to_string(num1);
}
void operator1() {
++num1;
}
float operator2() {
num1--;
return num1;
}
};
int main()
{
OP p(2);
p.operator1();
std::cout << p.print() << std::endl;
p.operator2();
std::cout << p.print() << std::endl;
return 0;
}