【问题标题】:accessing private members of a class in cuda kernel访问 cuda 内核中类的私有成员
【发布时间】:2011-08-27 01:37:29
【问题描述】:

我创建了一个类并将其对象传递给 cuda 内核。

内核的代码是:

__global__ void kernel(pt *p,int n)
{
int id=blockDim.x*blockIdx.x+threadIdx.x;
if(id<n)
{
    p[id]=p[id]*p[id];
}}

它给出了以下错误:error: ‘int pt::a’ is private

问题是: 如何访问类的私有成员?

如果没有私有成员,程序就可以运行

class pt{
int a,b;
public:
pt(){}
pt(int x,int y)
{
    a=x;
    b=y;
}
friend ostream& operator<<(ostream &out,pt p)
{
    out<<"("<<p.a<<","<<p.b<<")\n";
    return out;
}
int get_a()
{
    return this->a;
}
int get_b()
{
    return this->b;
}
__host__ __device__ pt operator*(pt p)
{
    pt temp;
    temp.a=a*p.a;
    temp.b=b*p.b;
    return temp;
}
pt operator[](pt p)
{
    pt temp;
    temp.a=p.a;
    temp.b=p.b;
    return temp;
}
void set_a(int p)
{
    a=p;
}
void set_b(int p)
{
    b=p;
}};

【问题讨论】:

  • pt的定义是什么?
  • 您的函数似乎在类定义之外被声明为友元。 pt类的定义是什么?除非友元函数在类定义中声明,否则它不是类的友元。

标签: c++ cuda private-members


【解决方案1】:

类的私有成员只能由其成员函数及其朋友访问。

【讨论】:

    【解决方案2】:

    您的 C++ 代码中有一些错误。

    这在我的机器上编译(CUDA 4.0 Mac Osx)

    #include <iostream>
    
    class pt {
        int a,b;
    public:
        __host__ __device__ pt(){}
        __host__ __device__ pt(int x,int y) : a(x), b(y)
        {
        }
    
    int get_a()
    {
        return this->a;
    }
    int get_b()
    {
        return this->b;
    }
    
    __host__ __device__ pt operator*(pt p)
    {
        pt temp;
        temp.a=a*p.a;
        temp.b=b*p.b;
        return temp;
    }
    pt operator[](pt p)
    {
        pt temp;
        temp.a=p.a;
        temp.b=p.b;
        return temp;
    }
    void set_a(int p)
    {
        a=p;
    }
    void set_b(int p)
    {
        b=p;
    }
    
    friend std::ostream& operator<<(std::ostream &out,pt p);
    
    };
    
    std::ostream& operator<<( std::ostream &out,pt p)
    {
        out<<"("<<p.a<<","<<p.b<<")\n";
        return out;
    }
    
    __global__ void kernel(pt *p,int n)
    {
    int id=blockDim.x*blockIdx.x+threadIdx.x;
    if(id<n)
    {
        p[id]=p[id]*p[id];
    }}
    

    【讨论】:

      猜你喜欢
      • 2018-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 2013-01-09
      • 2016-07-10
      相关资源
      最近更新 更多