为什么这个条件 return 为假,但在 main 函数中它 return 为真?

Why does this condition return false, but in the main function it returns true?

所以我正在研究 C++ 中的模板并且我有这个模板 class, "Test.h":

#ifndef TEST_H
#define TEST_H

#include <cassert>
#include <iostream>
#include <cmath>    // for std::abs

template<unsigned int DIM> class Test
{
private:
    double abs_error = 1e-6;
    double mData[DIM];

public:
    double& operator[](int index)
    {
        // To check that the input index is a valid one
        assert(index < DIM);
        assert(index > -1);

        // Condition that checks for values between 0 and 1 inclusive
        if (mData[index] >= 0.0 && mData[index] <= 1.0)
        {
            return mData[index];
        }

        // Values less than zero
        else if (std::abs(mData[index]) <= abs_error && mData[index] <= 0.0)
        {
            return mData[index] = 0;
        }

        // Values more than one
        else if (mData[index] >= 1.0 && std::abs(mData[index] - 1.0) <= abs_error)
        {
            std::cout << "You used this condition." << std::endl;
            return mData[index] = 1;
        }

        // For every other possible value
        else
        {
            assert(0);
        }

        return mData[index];

    }



};


#endif //TEST_H

它从技术上检查分配给数组中特定索引的值。我想要它做的是,如果数字介于 0 和 0.000001 之间,我希望它为该特定索引 return 0。如果数字介于 1 和 1.000001 之间,我希望它将分配给该特定索引的值更改为 1。如果数字小于零或大于一,我希望它引发断言语句,例如,如果存储在数组特定索引中的值为 2 或 -0.3。

因此,我在主文件中对其进行了测试: "main.cpp"

#include <iostream>
#include <cmath>
#include "Test.h"

int main()
{
    Test<6> p;
    p[0] = 0.5;
    std::cout << "p[0]: " << p[0] << std::endl;
    p[1] = -1e-7;
    std::cout << "p[1]: " << p[1] << std::end;
    // Comment the following two lines and check the test statement
    p[2] = 1+1e-8;
    std::cout << "p[2]: " << p[2] << std::endl;

    // This code tests the same condition as in Test.h for 
    // values more than one
    bool foo = 1+1e-8 >= 1.0 && std::abs(1+1e-8 - 1.0) <= 1e-6;
    std::cout << "foo (should return 1): " << foo << std::endl;

    return 0;
}

因此,在“main.cpp”文件中,第一个值为 0.5,因此它检查为 true,因为它介于 0 和 1 之间(含)。

下一个也 return 正确,因为它介于 0 和 0.000001 之间(含),因此它被分配为 0 并且应该在屏幕上打印它。

但是第三个提出断言,但是如果您注释掉该部分并将测试语句留在文件底部,它将 return 为真,即使它是相同的逻辑条件。

我的问题是,我做错了什么?

编辑: 如果我在 Linux Ubuntu 14.06 中编译它不会工作,但如果我在 OS X Yosemite 有效。

问题可能是您没有初始化这些值。

行如

p[0] = 0.5;

也叫double& operator[]。但是当第一次赋值时,结果已经取决于你记忆中的内容。如果它小于 1+abs_error 一切都很好,如果不是,它会引发 assert(0).

所以你应该用至少不会引发断言的东西来初始化你的数组,例如{0}