2015-10-18 99 views
0

爲SquareValue設置以下構造函數的正確方法是什麼? 我收到以下錯誤:在類構造函數中使用單獨類的對象

「構造函數SquareValue必須明確地初始化成員‘’不具有默認構造函數」方

#include <iostream> 
#include <string> 

using std::cout; 
using std::endl; 
using std::string; 

class Square { 

public: 
int X, Y; 

Square(int x_val, int y_val) { 
    X = x_val; 
    Y = y_val; 
} 

}; 


class SquareValue { 

public: 

Square square; 
int value; 

SquareValue(Square current_square, int square_value) { 
    square = current_square; 
    value = square_value; 
} 
}; 

我曾計劃經過廣場()構造函數到SquareValue構造函數中。

回答

4

當你不使用在構造函數列表初始化語法初始化一個對象,默認的構造函數用於:

SquareValue(Square current_square, int square_value) { 
    square = current_square; 
    value = square_value; 
} 

等同於:

SquareValue(Square current_square, int square_value) : square() { 
    square = current_square; 
    value = square_value; 
} 

square()是因爲有問題Square沒有默認構造函數。

使用:

SquareValue(Square current_square, int square_value) : 
    square(current_square), value(square_value) {} 
+1

廣場構造可選地更改爲'廣場(INT x_val = 0,INT y_val = 0)',以便它可以是默認構造。 –

+0

謝謝,我使用初始化語法完成了一些故障排除,但似乎沒有發現。 – Mars01