I just learned that I can define function function in separate files than main.cpp as long as I declared the function in main.cpp and compile it using g++ main.cpp message.cpp
.
But what if I want to define a class in separate files than main.cpp? It doesn't seems to work and I don't know what to declare in main.cpp while defining that class in separate files. Thanks.
Edit:
Here is main.cpp code:
#include <iostream>
#include <string>
using namespace std;
int main() {
int a, b;
string str;
Fraction fract;
while (true) {
cout << "Enter numerator: ";
cin >> a;
cout << "Enter denumerator: ";
cin >> b;
fract.set(a, b);
cout << "Numerator is " << fract.get_num()
<< endl;
cout << "Denumerator is " << fract.get_den()
<< endl;
cout << "Do it again? (y or n) ";
cin >> str;
if (!(str[0] == 'y'))
break;
}
return 0;
}
And here is Fraction.cpp
#include <cstdlib>
class Fraction {
private:
int num, den;
public:
void set(int n, int d) {
num = n;
den = d;
normalize();
}
int get_num() {
return num;
}
int get_den() {
return den;
}
private:
void normalize() {
if (den == 0 || num == 0) {
num = 0;
den = 1;
}
if (den < 0) {
num *= -1;
den *= -1;
}
int n = gcf(num, den);
num = num / n;
den = den / n;
}
int gcf(int a, int b) {
if (b == 0)
return abs(a);
else
return gcf(b, a%b);
}
int lcm(int a, int b) {
int n = gcf(a, b);
return a / n * b;
}
};
But I can't compile it with g++ main.cpp Fraction.cpp
.
Edit2:
It gives me error:
main.cpp: in function 'int main()':
main.cpp:8:3: error: 'Fraction' was not declared in this scope
main.cpp:14:15: 'fract' was not declared in this scope