首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >c++编程问题

c++编程问题
EN

Stack Overflow用户
提问于 2011-05-13 12:28:49
回答 6查看 2.2K关注 0票数 0

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

代码语言:javascript
复制
#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();
}

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

代码语言:javascript
复制
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)在做什么。请给我解释一下这个代码。

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2011-05-13 12:34:34

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

在使用之前声明它。添加

代码语言:javascript
复制
int julia(int x, int y); 

在定义kernel()之前。您还可以将整个julia()函数定义移到kernel()之前,以避免错误。

谁能给我解释一下 cuComplex cuComplex( float a,float b)中的代码行: r(a),i(b){}这段代码是做什么的?

代码语言:javascript
复制
cuComplex( float a, float b ) : r(a), i(b){} 

使用称为Initializer List的C++概念来初始化您的成员r & i

它在这里主要做的是:

代码语言:javascript
复制
r = a;
i = b;

我们可以在structure中创建构造函数吗?

是的,你可以在结构中有一个构造函数。除了缺省访问说明符之外,C++结构和类之间没有区别,在的情况下是私有,而在结构的情况下是公共

票数 5
EN

Stack Overflow用户

发布于 2011-05-13 12:44:04

您需要在using namespace std;行的下面插入int julia(int,int);

票数 2
EN

Stack Overflow用户

发布于 2011-05-13 12:42:00

这里没有使用函数原型化的概念...根据ANSI标准,我们必须在第一次使用函数之前声明函数,或者至少在使用函数进行成功编译之前必须清楚地声明函数的签名。

定义可以在linking...if时可用,该函数在其他文件中签名应以关键字‘extern’为前缀...

代码看起来是正确的.

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5987224

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档