拆分函数的声明和定义,还是删除函数头中的新运算符?

Split function's declaration and definition, or delete new operator in header?

我是C++的新手,在我的项目中遇到了困难。

Super.h

#pragma once
#include <iostream>

float *list=new float[10];

class Super{
public:
    void function(){}
};

A.h

#pragma once
#include "Super.h"

class A{  
public:
    void function();
};

A.cpp

#include "A.h"
void A::function(){
    std::cout<<"Working A!"<<std::endl;
}

main.cpp

#include "A.h"

int main(int argc, const char * argv[]) {
    A a;
    a.function();
    return 0;
}

此代码未编译,(clang: error: linker command failed with exit code 1 (use -v to see invocation)) and I found if I delete

float *list=new float[10];

在Super.h,编译成功。

但是我需要classA中可以访问到的数组,所以试了很多方法,发现留float数组可以编译,结合A.h和A.cpp,喜欢

//Super.h    

float *list=new float[10];

class Super{

public:
    void function(){}
};

------------------------------------
// A.h

#pragma once
#include "Super.h"


class A{

public:    
    void function();
};

void A::function(){
    std::cout<<"Working A!"<<std::endl;
}

我必须结合使用 A.cpp 和 A.h 吗?还是我的设计不好?我用 XCode 8.

在您的实际代码中,“line”在 Settings.h 中声明并在其 drawPixel 函数中使用。

唯一使用它的地方是 main.cpp 我将以相反的顺序讨论这些要点,以便我们的讨论更有意义:

  • 清理:delete[] pixels 你应该使用 vector<float> 来避免所有与动态内存相关的问题:
    1. 如果在清理后调用 drawPixel 怎么办?
    2. 如果您的代码因错误退出怎么办?
    3. 您将如何确保您的 main 函数不会提前退出并错过这个?
  • 用法:glDrawPixels(width, height, GL_RGB, GL_FLOAT, pixels) 最后一个 glDrawPixels 参数的类型是 void* 所以,如果你正确地用 vector<float> 替换了 pixels 你可以通过传递 data(pixels)
  • 进行隐式转换
  • 初始化:fill_n(pixels, width*height * 3, 1.0f) 而不是 Settings.h,这是应该定义 pixels 的地方:vector<float> pixels(width * height * 3, 1.0F) 您需要对系统进行这些更改以避免全局变量:
    1. void draw() 的所有实例都需要更改为 void draw(vector<float>& pixels),并且当调用任何 draw 方法时,pixels 将成为参数
    2. void drawPixel(const int& i, const int& j, const float& red, const float& green, const float& blue) 应更改为 void drawPixel(vector<float>& pixels, const int i, const int j, const float red, const float green, const float blue) 并且对 drawPixel 函数的任何调用都必须采用 pixel 因为它是 1st 争论
    3. void drawLine(const int& i0, const int& j0, const int& i1, const int& j1, const float& red, const float& green, const float& blue) 应更改为 void drawLine(vector<float>& pixels, const int i0, const int j0, const int i1, const int j1, const float red, const float green, const float blue) 并且对 drawLine 函数的任何调用都必须采用 pixel 因为它是 1st 争论