所以我学习的模板在C++和我有这个模板类,“Test.h”:为什么此条件返回false,但在主函数中返回true?
#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之间,我希望它为该特定索引返回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之间。
下一个也返回true,因为它介于0和0.000001之间,所以它被赋值为0并且应该在屏幕上打印它。
但是第三个提出了断言,但是如果您将该部分注释掉并将测试语句留在文件底部,它将返回true,即使它是相同的逻辑条件。
我的问题是,我在这里做错了什么?
编辑:如果我在Linux Ubuntu 14.06编译它不会工作,但如果我在OS X Yosemite编译它的作品。
您的运算符根本不返回布尔值。它返回一个'double&'。 – paddy
似乎在这里工作[演示](https://ideone.com/X9e3S1)。 – Jarod42
“p.mData”的条目是否已初始化? –