gpt4 book ai didi

c++ - 无法将成员函数从类型 'double (ClassOne::)()' 转换为类型 'double (ClassOne::*)()'

转载 作者:太空宇宙 更新时间:2023-11-04 11:23:19 25 4
gpt4 key购买 nike

我创建了一个类,想通过C++中的generate_n来初始化参数。

代码如下:

#include <algorithm>
#include <math.h>

using namespace std;

class HiddenLayer
{
public:

double *W;
double *b;

ClassOne(int low, int high)
{
this->low = low;
this->high = high;

this->W = new double[100];
this->b = new double[100];

generate_n(W, 100, uniform);
};

~ClassOne()
{
delete[] W;
delete[] b;
};

private:
double low;
double high;

double uniform() {
return rand() / (RAND_MAX + 1.0) * (high - low) + low;
};
};

而且报错是cannot convert 'ClassOne::uniform' from type 'double (ClassOne::)()' to type 'double (ClassOne::*)()', what错误代表什么?

最佳答案

这个错误是因为你必须使用&ClassOne::uniform来取一个成员函数的地址;成员函数不像自由函数那样隐式衰减到指向成员的指针。

但是,一旦您进行了此修复,您将遇到不同的错误;您不能将成员函数用作 generate_n 的仿函数。它必须接受一个自由函数,或者一个定义了 operator() 的对象。

在 C++11(或之前的 boost::function)中,有一个名为 std::function 的预设仿函数模板,您可以从带参数的函数和给定的参数创建它使用 std::bind 的参数,其中成员函数被视为具有隐藏的 this 参数的函数;代码是:

auto f = bind( &ClassOne::uniform, this );
generate_n(W, 100, f);

关于c++ - 无法将成员函数从类型 'double (ClassOne::)()' 转换为类型 'double (ClassOne::*)()',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27538775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com