# c++ /c class問題

#include<iostream>

using namespace std;class Rational

{

private:

int a;

int b;

public:

Rational();

Rational(int,int);

Rational operator +(Rational &);

Rational operator -(Rational &);

Rational operator *(Rational &);

Rational operator /(Rational &);

void show();

int gcd(int,int);

};

int main()

{

Rational A(2,6),B(1,21),C;

A.show();

cout<<"+";

B.show();

cout<<"=";

C=A+B;

C.show();

system("pause");

return 0;

}

Rational::Rational()

{

}

Rational::Rational(int x,int y)

{

if(y==0)

{

cout<<"分母不能為0"<<endl;

system("pause");

}

int g;

g=gcd(x,y);

a=x/g;

b=y/g;

}

int Rational::gcd(int m,int n)

{

do

{

if(m>n)

m=m%n;

else

n=n%m;

}while(m*n);

if(m)

return m;

else

return n;

}

void Rational::show()

{

cout<<"("<<a<<"/"<<b<<")";

}

Rational::Rational operator +(Rational &s)

{

Rational m;

int q;

m.a=a*s.b+b*s.a;

m.b=b*s.b;

q=gcd(m.a,m.b);

m.a=m.a/q;

m.b=m.b/q;

return m;

}

### 1 個解答

• 1 0 年前
最佳解答

Rational Rational::operator +(Rational &s)

{

Rational m;

int q;

m.a=a*s.b+b*s.a;

m.b=b*s.b;

q=gcd(m.a,m.b);

m.a=m.a/q;

m.b=m.b/q;

return m;

}

單純只是"屬於"符號標錯位置

所以他讀不到private的東西

(型態 class名稱::funtion名稱)