在其他类构造函数中使用类作为类型

Wen*_*del 0 c++ constructor class

我想在其他类 Rect 中使用类 Point。

\n
class Point\n{\n    int x, y;\n    public:\n    Point (int px, int py){\n        x = px;\n        y = py;\n    }\n};\n\nclass Rect\n{\n    Point top_left; \n    Point bottom_right;\n    public:\n    Rect (Point p1, Point p2){\n        top_left = p1;\n        bottom_right = p2;\n    }\n};\n
Run Code Online (Sandbox Code Playgroud)\n

错误消息是:“ main.cpp:31:30: 错误:没有调用 \xe2\x80\x98Rect::Point::Point()\xe2\x80\x99 的匹配函数”。根据我的理解, Rect 类的构造函数方法使用两个 Point 类型的参数来实例化 Rect 对象。我想我不能使用“Point”作为类型,因为它听起来像是编译器想要调用一个函数。错误消息对我没有帮助,所以我希望你能帮我。预先感谢您。

\n

for*_*818 5

成员在构造函数主体运行之前初始化。当你写:

Rect (Point p1, Point p2){
    top_left = p1;
    bottom_right = p2;
}
Run Code Online (Sandbox Code Playgroud)

然后在执行构造函数之前,对成员top_leftbottom_right进行初始化。由于Point没有默认构造函数,因此无法初始化成员。

要使用构造函数初始化成员,您应该使用成员初始值设定项列表:

Rect (Point p1, Point p2) : top_left(p1), bottom_right(p2) { }
Run Code Online (Sandbox Code Playgroud)

还可以通过为成员提供默认初始值设定项来防止该错误:

class Rect
{
    Point top_left{0,0}; 
    Point bottom_right{0,0};
    public:
    Rect (Point p1, Point p2){
        top_left = p1;
        bottom_right = p2;
    }
};
Run Code Online (Sandbox Code Playgroud)

或者通过为 提供默认构造函数Point。默认构造函数是可以不带参数调用的构造函数。但是,无论如何,您应该更喜欢使用成员初始值设定项列表而不是构造函数主体中的赋值,因为初始化 + 赋值比仅初始化更昂贵。