c++编程问题

标签 c++ c

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

#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();
}

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

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

我做错了什么? julia 在那里定义,为什么它显示问题? 任何人都可以向我解释一下 C++ 中的函数范围吗?

谁能给我解释一下 struct cuComplex 中的代码行 cuComplex( float a, float b ) : r(a), i(b){} 这段代码在做什么? 我们可以在结构中创建构造函数吗?或者这个 r(a), i(b) 在做什么。 请为我解释这段代码。

最佳答案

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

在使用前声明它。添加

int julia(int x, int y); 

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

任何人都可以向我解释 struct cuComplex cuComplex( float a, float b ) : r(a), i(b){} 中的代码行吗?

cuComplex( float a, float b ) : r(a), i(b){} 

利用了一个名为 Initializer List 的 C++ 概念初始化您的成员 r & i .
它基本上在这里做的是:

r = a;
i = b;

我们可以在结构中创建构造函数吗?
是的,你可以在结构中有一个构造函数。除了默认访问说明符外,C++ 结构和类之间没有区别,对于private strong> 但在结构 的情况下public

关于c++编程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5987224/

相关文章:

c++ - 'delete' 的数组形式是什么?

c++ - 测试换行符

C++ 使用 *this 从静态方法调用抽象方法

C++ 类变量不保留值

c - 大数组在 C 中给出段错误

c# - 打印带有字母的倒三角形

缺少库的 C++ 项目编译和链接

c - 局部变量不是静态的,但为什么会出现这种行为?

无法让这个 "Conditional Operator"程序运行

c - 打印值,C