2015-10-18 71 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

相关问题