简体   繁体   English

在cuda内核中访问类的私有成员

[英]accessing private members of a class in cuda kernel

I created a class and passed its object to a cuda kernel. 我创建了一个类并将其对象传递给cuda内核。

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 并且它给出以下错误: 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;
    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;
}};

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

There are some errors in your C++ code. 您的C ++代码中存在一些错误。

This compiles on my machine (CUDA 4.0 Mac Osx) 这在我的机器上编译(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];
}}

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

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