2014-05-10 54 views
1

我想學習C++中類的概念。我編寫了一些代碼來測試我所知道的,編譯代碼時,第一個錯誤是:「沒有匹配函數調用'base :: base()' base base1,base2;」在C++中調用沒有匹配函數

我不知道爲什麼!

這裏是整個代碼:

#include <iostream> 
using namespace std; 

class base { 
    int x, y; 
    public: 
    base (int, int); 
    void set_value (int, int); 
    int area() { return (x*y); } 
}; 
base::base (int a, int b) { 
x = a; 
y = b; 
} 
void base::set_value (int xx, int yy) { 
x = xx; 
y = yy; 
} 
int main() { 
base base1, base2; 
base1.set_value (2,3); 
base2.set_value (4,5); 
cout << "Area of base 1: " << base1.area() << endl; 
cout << "Area of base 2: " << base2.area() << endl; 
cin.get(); 
return 0; 
} 

回答

2

可以使用

base base1, base2; 

時,纔會有辦法用base默認構造函數。由於base已經明確定義了一個非默認的構造函數,所以默認構造函數不再可用。

您可以通過多種方式解決這個問題:

  1. 定義默認構造函數:

    base() : x(0), y(0) {} // Or any other default values that make more 
             // sense for x and y. 
    
  2. 在構造函數中提供的參數的默認值,您有:

    base(int a = 0, int b = 0); 
    
  3. 使用有效參數構造這些對象。

    base base1(2,3), base2(4,5); 
    
1

base base1, base2;嘗試使用默認構造函數構造兩個base對象爲base(即base::base()base沒有默認的構造函數,所以這並不編譯。

爲了解決這個問題,請將缺省構造函數添加到base(聲明並定義base::base()),或使用您已定義的雙參數構造函數,如下所示:

base base1(2,3), base2(4,5);