c++ - 为什么我不能在这里使用成员初始化列表?

标签 c++

我刚刚创建了一个“Point”类,正在处理一个“Line”类,它有两个 Point 对象(Point 起点和 Point 终点)作为数据成员。我在我的 Line 类中创建了一个构造函数,它接受两个 Point 对象作为参数,最初创建它的方式如下:

Line(const Point& p1, const Point& p2)
{
    startpoint = p1;
    endpoint = p2;
}

一切都很好,但后来我决定使用成员初始化列表而不是将成员分配给正文中的 p1 和 p2,只是因为......但是当我将其更改为:

Line(const Point& p1, const Point& p2): startpoint(p1), endpoint(p2)
{
}

我收到一条错误消息“没有构造函数“Point::Point”的实例与参数列表匹配”并且不明白这到底是什么意思。

为什么成员初始化列表在这里不起作用?

谢谢。

编辑:抱歉,我不知道我的积分等级的细节是否相关:

//点.h

class Point
{
private:
    double x;
    double y;

public:
    Point();
    Point(Point& p);
    Point(double x1, double y1);
    ~Point();

    double X() const;
    double Y() const;

    void X(double newx);
    void Y(double newy);
    };

//点.cpp

#include "Point.h"

Point::Point(): x(0), y(0)
{
}

Point::Point(Point& p)
{
    x = p.x;
    y = p.y;
}

Point::Point(double x1, double y1): x(x1), y(y1)
{
}

Point::~Point()
{
}

double Point::X() const
{
    return x;
}

double Point::Y() const
{
    return y;
}

void Point::X(double newx)
{
    x = newx;
}

void Point::Y(double newy)
{
    y = newy;
}

最佳答案

成员初始化取决于具有公共(public)复制构造函数的 Point,因为您显式调用了 Point::Point(const Point&)

如果它不存在或不可访问,则不能调用它。如果您不能调用它,那不是因为初始化列表 不起作用。

如果第一个版本有效,大概 Point 有一个可访问的赋值运算符。


确认一下,现在您已经粘贴了 Point 的源代码,复制构造函数应该如下所示:

Point::Point(const Point &other) : x(other.x), y(other.y) {}

(您可能会习惯于使用初始化列表)。 关键的变化是参数必须是 const 引用:这可以防止在复制时意外损坏源对象。

关于c++ - 为什么我不能在这里使用成员初始化列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8792763/

相关文章:

c++ - C++代码中的错误可能是指针未指向任何东西

c++ - 强制 CMake/VisualStudio 使用 Boost.Python 的静态库

c++ - SFML 2.0 GLSL 体积光散射着色器

c++ - Armadillo 库会减慢矩阵运算的执行速度吗?

c++ - 从视频中提取声音

c++ - QNetworkAccessManager - 没有这样的信号

c++ - CMake 与 Visual Studio

c++ - 如何使用 C/C++ 在 Linux 中通过提供进程 ID 来获取父进程 ID?

c++ - 调用函数并向其传递限制限定指针是否危险?

C++、Allegro、Ubuntu 和 libpng/LoadPNG