开发者

accessing private members of a class in cuda kernel

I created a class and passed its object to a cuda kernel.

The kernel's code is:

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

And it gives the following error: error: ‘int pt::a’ is private

The Question is: How can I access the private member of a class?

The program runs all right if there are no private members

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;
    te开发者_Go百科mp.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;
}};


Private members of a class can only be accessed by its member functions and its friends.


There are some errors in your C++ code.

This compiles on my machine (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];
}}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜