类型为'double *'和'double'的二进制'operator +'

时间:2015-10-03 15:58:59

标签: c++

这是我试图实现的模板类:

#ifndef __ENCRYPTION_HEADER_INCLUDED__
#define __ENCRYPTION_HEADER_INCLUDED__

#include <iostream>  // in/out 
#include <fstream>   // file
#include <string>    // string
#include <sstream>   // string stream

using namespace std; // standard namespacing eliminates std:: from code


template <class mytemp>
class encryption 
{   
    public:

        mytemp * p;   

        encryption(); 

        mytemp encrypt_function (mytemp);
};


template <class mytemp>
encryption<mytemp>::encryption ()
{
    string line_in, file_name;
    mytemp input_value;

    cout << "input file name which contains encryption keys: " ;
    getline(cin, file_name);
    cout << '\n';   
    ifstream val_file (file_name.c_str());

    p = new mytemp[10];

    if (val_file.is_open())
    {
        while (getline(val_file, line_in))
        {
            istringstream line_out(line_in);
            line_out >> hex >> input_value;

            *p = input_value;
            p++;
        }

        p -= 10;
        val_file.close();
    }
    else
    {
        cout << "file not found" << '\n';
    }
}

template <class mytemp>
mytemp encryption<mytemp>::encrypt_function (mytemp input_en)
{
    mytemp output_en = input_en;

    for (mytemp k = 0; k < 10; k++)
    {
        output_en ^= *(p + k); // does not work with double or float but works with int?
    }
    return output_en;
}

#endif // __ENCRYPTION_HEADER_INCLUDED__ 

下面显示的是我遇到问题的一行:

output_en ^= *(p + k); // does not work with double or float but works with int? 

我的理解是这对于一个整数是正确的,但它不适用于double或float,我想知道是否有一种简单的方法可以让它工作,而不是重写代码来增加指针而不是递增指向价值观?

2 个答案:

答案 0 :(得分:0)

指针算术需要带符号整数(即std::ptrdiff_t)类型,其中double或float都不是。在这个循环中:

for (mytemp k = 0; k < 10; k++)
{
    output_en ^= *(p + k); // does not work with double or float but works with int?
}

使用float或double是没有意义的。只需使用signed int(int是)。

答案 1 :(得分:0)

不为这些类型定义按位xor。如果您只是将输入解释为位,那么您应该执行memcpy()memset()所做的操作,并将它们解释为无类型的字节数组。也就是说,您的模板包装器可以确定数据的地址和大小,并将它们传递给与内存块相关的函数。

相关问题