2016-09-03 65 views
-2

我只是在異常處理方面嘗試一個示例。 我收到錯誤錯誤:'operator >>'不匹配 我的程序出了什麼問題。 我正在使用linux gcc。錯誤:'operator >>'不匹配

#include<iostream> 
using namespace std; 
void div(double, double); 
void read (double *, double *); 
main() 
{ 
    double a,b; 
    cout<<"enter the two nos"; 
    cin>>a>>b; 
    read(&a,&b); 
    div(a,b); 
} 

void div(double a, double b) 
{ 
    double d; 
    try { 
     if(b==0) 
     throw "divide by zero condition occured"; 
     d=a/b; 
     cout<<"divsion of two no is"<<d<<endl; 
    }catch(const char *e) 
    { 
     cout<<"exception is "<<e<<endl; 
    } 
} 
void read(double *a,double *b) 
{ 
    cout<<"Enter the 2 no."; 
    cin>>a>>b; 
} 

我也嘗試另一個函數讀取功能

void read(double *a,double *b) 
{ 
    double c,d; 
    cout<<"Enter the 2 no."; 
    cin>>c>>d; 
    a=c; 
    b=d; 
} 

,但它也有錯誤:

cannot convert ‘double’ to ‘double*’ in assignment

+1

你可能想要在你的問題完整的錯誤消息。 –

+0

Typo。你需要在'read'中解除'a'和'b'的引用。 – NathanOliver

+0

通過參考。它將消除這些指針缺陷。 –

回答

0
void read(double *a,double *b) 
{ 
    double c,d; 
    cout<<"Enter the 2 no."; 
    cin>>c>>d; 
    a=c; 
    b=d; 
} 

這不起作用,因爲你想改變指針指向的值而不是指針本身導致的錯誤。它修復了這一點:

void read(double *a,double *b) 
{ 
    double c,d; 
    cout<<"Enter the 2 no."; 
    cin>>c>>d; 
    *a=c; 
    *b=d; 
} 

當然,在這種情況下,我不建議使用指針,最好使用引用,所以不需要提領,你可以這樣調用它read(a,b)

void read(double &a,double &b) 
{ 
    double c,d; 
    cout<<"Enter the 2 no."; 
    cin>>c>>d; 
    a=c; 
    b=d; 
} 

double& b表示法意味着通過引用。您也可以爲其他讀功能相同的問題,解決這個:

void read(double *a,double *b) 
{ 
    cout<<"Enter the 2 no."; 
    cin>>*a>>*b; 
} 

或更好:

void read(double &a,double &b) 
{ 
    cout<<"Enter the 2 no."; 
    cin>>a>>b; 
} 
+0

臨時是多餘的;我不知道你爲什麼暗示他們。 –

0

你必須要分配給該指針的值:

*a=c; 
*b=d; 
1

變量a指針double
變量cdouble
表達式a = c;指定double指針double

嘗試:*a = c;

1
void read(double *a,double *b) 
{ 
    cout<<"Enter the 2 no."; 
    cin>>a>>b; 
} 

改變這對

void read(double *a,double *b) 
{ 
    cout<<"Enter the 2 no."; 
    cin>>*a>>*b; 
} 

因爲對象cin有一個稱爲operator>>方法,該方法是重載採取不同類型的數據時的工作。像operator>>(short& __n)輸入short數據類型,operator>>(float& __f)輸入float數據類型。但是該方法的重載版本不需要double*作爲參數。並在代碼abdouble*。 如此參考ab返回double並且有一個operator>>的重載版本,其中double作爲參數是operator>>(double& __f)。因此,將cin>>a>>b更改爲cin>>*a>>*b將按預期工作。

+0

_Explain_您的答案不要只是代碼轉儲。 –

+0

瞭解@LightnessRacesinOrbit –