没有默认构造函数的成员对象的 C++ 初始化:

时间:2021-02-26 10:47:20

标签: c++ object default-constructor

类似的问题已得到解答,但我仍然无法找到解决我的问题的方法。我确实无法在类 Rectangle 中调用类 Point 的构造函数。在阅读了一些答案后,我大概会这样做,但它不起作用:

class Point {
public:
  Point(int x, int y);

private:
  int x;
  int y;
};

Point::Point(int xx, int yy) {
  x = xx;
  y = yy;
}

class Rectangle {
public:    
    Rectangle(Point a, Point b) : Point(int x, int y); // this is wrong
 
private:
    Point a;
    Point b;
};

Rectangle::Rectangle(Point aa, Point bb) :  Point(int x, int y) { // same as above
    ?
}

谁能帮助我理解如何实现和修复这段代码(我知道将 Rectangle 声明为结构体会更容易)?

1 个答案:

答案 0 :(得分:3)

不清楚你期望这条线做什么:

Rectangle(Point a, Point b) : Point(int x, int y);

初始化成员的地方不是构造函数体。成员启动器列表的正确语法是:

Rectangle(Point a, Point b) : a(a), b(b) {}

注意初始化列表是一个不存在阴影的地方,参数和成员可以使用相同的名称,因为没有歧义。 a(a) 使用参数 a 初始化成员 a


注意 Point 的构造函数也应该是:

Point::Point(int xx, int yy) : x(xx),y(yy) {
}

对于 int 成员,它不会有很大的不同,但对于类类型,它确实有很大的不同:成员在构造函数体运行之前被初始化。 Fist 初始化然后在构造函数中赋值是低效的,有时是错误的。另一方面,当成员是 int 时,没有理由不使用初始化列表。


附注

<块引用>

(我知道将 Rectangle 声明为结构体会更容易)?

我认为您指的是结构中的公共成员。但是,structclass 只是用于声明类的两个不同关键字。唯一的区别是默认访问权限(请参阅此处了解详细信息:When should you use a class vs a struct in C++?)并且这两个定义是相同的:

class foo { 
    int a;
public:
    int b;
};
struct foo {
private:
    int a;
public:
    int b;
};