柚子 發問時間: 電腦與網際網路程式設計 · 1 0 年前

c++ /c class問題

我想寫一個有理數的加減乘除,我不太懂為什麼會出現private a,b的警告

可否告訴我錯在哪 如何更改程式碼在不更動private a,b的情況

#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名稱)

還有問題?馬上發問,尋求解答。