成员初始化列表中初始化的向量与传递给构造函数的数字不同

Vectors initialised in member initialisation list not the same as passed to constructor..?

本文关键字:初始化 构造函数 数字 列表 向量 成员      更新时间:2023-10-16

我正在尝试创建一个简单的表类,其中包含两个具有成员初始化列表的向量:

table.hh

class Table
{
public:
    Table(vector<double> a, vector<double> b);
    ~Table();
    double interpolate(double val, bool extrapolate = true);
    double integrate();
    void print();
private:
    vector<double> x, y;
};

table.cc

Table::Table(vector<double> a, vector<double> b)
: x(a), y(b)
{
    cout << this->x.size() << " " << this->y.size() << endl;
    try
    {
        if (this->x.size() != this->y.size())
            throw LengthException();
    }   
    catch(exception &e)
    {
        cout << e.what() << endl;
    }
}

当我尝试通过创建表的新实例来测试异常时:

vector<double> a = {1.0, 2.0, 3.0, 4.0};
vector<double> b = {1.0, 2,0, 3.0};
Table* mytable = new Table(a, b);

我发现例外没有被抛出,每个向量的大小都为4。

我无法立即看到为什么这是不预期的,有人可以提供帮助吗?

,因为向量b的大小为4:

我对您的代码进行了重新格式化,现在应该很明显:

vector<double> b = { 1.0,
                     2,
                     0,
                     3.0 };