c ++编程问题

use*_*164 0 c c++

嗨,我正在尝试编译一个c ++,程序为julia设置我的源代码如下

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<cpu_bitmap.h>
#include<book.h>

#define DIM 20
using namespace std;
struct cuComplex{
  float r;
  float i;
  cuComplex( float a, float b ) : r(a), i(b){}

  float magnitude2( void ) 
  { 
    return r * r + i * i; 
  }
  cuComplex operator*(const cuComplex& a)
  {
    return cuComplex(r*a.r - i*a.i, i*a.r + r*a.i);
  }
  cuComplex operator+(const cuComplex& a)
  {
    return cuComplex(r+a.r, i+a.i);
  }
};

void kernel( unsigned char *ptr )
{

  for (int  y=0; y<DIM; y++)
  {
    for ( int x=0; x<DIM; x++)
    {
      int offset = x + y * DIM;
      int juliaValue =julia( x, y );
      ptr[offset*4 + 0] = 255 * juliaValue;
      ptr[offset*4 + 1] = 0;
      ptr[offset*4 + 2] = 0;
      ptr[offset*4 + 3] = 255;
    }
  }
}

int julia( int x, int y ) 
{
  const float scale = 1.5;
  float jx = scale * (float)(DIM/2 - x)/(DIM/2);
  float jy = scale * (float)(DIM/2 - y)/(DIM/2);
  cuComplex c(-0.8, 0.156);
  cuComplex a(jx, jy);
  int i = 0;
  for (i=0; i<200; i++)
  {
    a = a * a + c;
    if (a.magnitude2() > 1000)
    {
      return 0;
    }
    return 1;
  }
}

int main( void )
{
  CPUBitmap bitmap( DIM, DIM );

  unsigned char *ptr = bitmap.get_ptr();

  kernel( ptr );
  bitmap.display_and_exit();
}
Run Code Online (Sandbox Code Playgroud)

但是当我编译它时,我得到以下错误:

compiling command : g++  -I /usr/local/cuda/include 5.cpp

errors:5.cpp: In function ‘void kernel(unsigned char*)’:
5.cpp:36: error: ‘julia’ was not declared in this scope
Run Code Online (Sandbox Code Playgroud)

我做错了什么?朱莉娅在那里被定义为什么它显示问题?任何人都能解释一下c ++中的函数范围吗?

任何机构都能解释一下struct cuComplex中的代码行 cuComplex( float a, float b ) : r(a), i(b){}这个代码在做什么?我们可以在结构中构造构造函数,或者r(a)是什么,i(b)正在做什么.请为我解释一下这段代码.

Alo*_*ave 5

该错误告诉您在使用之前kernel()需要知道函数的声明julia().在你的代码中它是在之后定义的kernel()

在使用前声明它.加

int julia(int x, int y); 
Run Code Online (Sandbox Code Playgroud)

kernel()定义之前.您也可以在julia()之前移动整个函数定义kernel()以避免错误.

任何机构都能解释一下struct cuComplex cuComplex中的代码行(float a,float b):r(a),i(b){}这段代码在做什么?

cuComplex( float a, float b ) : r(a), i(b){} 
Run Code Online (Sandbox Code Playgroud)

利用称为C++的概念Initializer List,以您的成员初始化ri.
这基本上是做什么的:

r = a;
i = b;
Run Code Online (Sandbox Code Playgroud)

我们可以在结构中构造构造函数吗?
是的,您可以在Structures中拥有构造函数.除了默认访问说明符之外,C++结构和类之间没有区别,默认访问说明符在类的情况下是私有的,但在结构的情况下是公共的.