2010-11-28 113 views
0

我無法讓編譯器接受我的下面定義的用戶數據類型(Term),它接受另一個用戶數據類型(Rational)作爲參數。任何關於如何做這項工作的建議都會很棒!用戶定義的數據類型,使用另一個用戶定義的數據類型作爲參數

#ifndef _TERM_H 
#define _TERM_H 

#include "Rational.h" 

using namespace std; 

class Term { 

public: 

    //constructors 
    Term(const Rational &a, const int &b) 
    { 
     this->coefficient = a; 
     this->exponent = b; 
    } 

    Term(){} 

    ~Term() {} 

    //print the Rational 
    void print()const 
    { 
     cout << coefficient << " x^" << exponent << endl; 
    } 

private: 

    Rational *coefficient, *a; 
    int exponent, b; 
}; 

#endif 

#ifndef _TERM_H 
#define _TERM_H 

using namespace std; 

class Rational { 

public: 

    //constructors 
    Rational(const int &a, const int &b){ 
     if (a != 0) 
      if (b != 0) 
       this->numerator = a; 
      this->denominator = b; 
    } 

    //print the Rational 
    void print()const { 
     cout << numerator << "/" << denominator << endl; 
    } 

    //add 2 Rationals 
    void add(const Rational &a, const Rational &b){ 
     numerator = ((a.numerator * b.denominator)+(b.numerator*a.denominator)); 
     denominator = (a.denominator*b.denominator); 
    } 

... 

    private: 
    int a, b, numerator, denominator; 
}; 

#endif 

我不斷收到以下錯誤消息。

Term.h(30):error C2440:'=':無法從'const Rational'轉換爲'Rational *' 1>沒有可執行此轉換的用戶定義轉換運算符或運算符不能稱爲 ==========生成:0成功,1失敗,0上最新,0已跳過==========

+0

請正確縮進您的代碼。它使我們更容易閱讀並幫助您。 – 2010-11-28 11:29:22

+0

切勿在標題中使用`using namespace std;`。對於這個問題,不要使用`使用xyz :: abc;`!包含此頭文件的每個文件都容易出現名稱空間衝突。 – rubenvb 2010-11-28 14:05:20

回答

1

首先,將coefficient的定義更改爲:

const Rational& coefficient; 

然後改變缺點tructor這樣:

Term (const Rational& a, const int& b) 
    : coefficient (a), exponent (b) 
{ 
} 
0
void print() const 
{ 
    cout << *coefficient << " x^" << exponent << endl; 
} 

你那裏不缺少一個解引用操作符?

1

你的問題是,Term::coefficient有類型Rational*(指向Rational的),在構造函數中,你試圖給該成員變量賦值Rational類型的值。

所以正確的構造函數,如果你想保留其餘完好,就像這樣:

Term(const Rational& a, int b) : coefficient(&a), exponent(b) {} 

或者你可以離開構造完整,更改專用部分:

private: 
    Rational coefficient; 
    // the rest of the member variables 
0

看來,你是在兩個不同的頭文件使用相同的包括後衛的名字(_TERM_H)。這非常糟糕 - 您需要在項目中的所有文件中包含唯一的保護名稱,否則包含一個文件會阻止其他文件。特別是,如果我正確地讀出你的代碼,你有這樣的:

#ifndef _TERM_H 
#define _TERM_H 
#include "Rational.h" 

而且Rational.h有這樣的:

#ifndef _TERM_H 
#define _TERM_H 

這應該意味着,當你有Rational.h,_TERM_H已經被定義,所以Rational.h的內容將被忽略。

相關問題