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;
}};
一个类的私有成员只能由其成员函数及其朋友访问。
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];
}}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.