繁体   English   中英

类型为'double *'和'double'的无效操作数到二进制'operator +'

[英]invalid operands of types 'double*' and 'double' to binary 'operator+'

这是我要实现的模板类:

#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,并且我想知道是否存在一种简单的方法来使它工作,而不是重写代码以增加指针而不是通过指向指针进行递增值?

指针算术期望带符号的整数 (即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?
}

使用浮点数或双精度数是没有意义的。 只需使用一个带符号的int(即int )。

未为这些类型定义按位异或。 如果将输入仅解释为位,则应该执行memcpy()memset()操作,并将它们解释为无类型的字节数组。 也就是说,您的模板包装器可以确定数据的地址和大小,然后将其传递给对内存块进行异或处理的函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM