访问cuda内核中类的私有成员
我创建了一个类并将其对象传递给 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;
}};
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;
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;
}};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
类的私有成员只能由其成员函数及其友元访问。
Private members of a class can only be accessed by its member functions and its friends.
您的 C++ 代码中有一些错误。
这可以在我的机器上编译(CUDA 4.0 Mac Osx)
There are some errors in your C++ code.
This compiles on my machine (CUDA 4.0 Mac Osx)