CodeBlocks编译器问题,C++

CodeBlocks compiler issue, C++

本文关键字:C++ 问题 编译器 CodeBlocks      更新时间:2023-10-16

我在C++中使用CodeBlocks,这可能是编译器的问题。我正在学习使用矢量指针,并试图创建返回矢量指针的函数。下面是我的代码。它以前在不使用指针的情况下编译和执行过。现在,我尝试使用一个返回指针的函数,但不知何故,它不起作用,我也无法找出错误。请帮忙。

错误:

main.cpp|8|undefined reference to `RandomNum::RandomNum(int, int, int, int)
main.cpp|9|undefined reference to `RandomNum::getVecPointer()

main.cpp

#include <iostream>
#include "RandomNum.h"
using namespace std;
int main()
{
    RandomNum rand(5, 5, 100, 1000);  <----error 
    vector<float>* p = rand.getVecPointer();
    cout << (*p)[0] << endl;
    return 0;
}

RandomNum.h

#include <vector>
#ifndef RANDOMNUM_H
#define RANDOMNUM_H
class RandomNum
    {
private:
    int M, x, y, z; //M is the number of cells
    std::vector <float> aVector;
public:
    //constructor
    RandomNum(int, int, int, int);
    //generate random float between 0 and 1;
    float unif();
    //build a vector of random points
    std::vector<float>* getVecPointer();
};
#endif

随机编号.cpp

#include "RandomNum.h"
#include <cmath>  //for trunc()
RandomNum::RandomNum( int MM,int xx, int yy, int zz )
{
    //x, y, z are seeds, M is the number of random numbers to be    generated [0,1]
    M = MM;
    x = xx;
    y = yy;
    z = zz;
}
float RandomNum::unif()
{
    float tmp;
    ...
    return(tmp - trunc(tmp));
}
std::vector<float>* RandomNum::getVecPointer()
{
    int i ;
    for (i = 0 ; i < M; i++)
    {
        float x = unif();
        aVector.push_back(x);
    }
    return &aVector;
}

无法重现您的问题。我下载了你的文件,并创建了一个Makefile:

OLIST += rand.o RandomNum.o
CFLAGS += -Wall -Werror
all: rand
%.o: %.cpp
    c++ $(CFLAGS) -c $<
rand: $(OLIST)
    c++ -o rand $(OLIST)
clean:
    rm -f *.o rand

这是制造商的输出:

c++ -Wall -Werror -c rand.cpp
c++ -Wall -Werror -c RandomNum.cpp
c++ -o rand rand.o RandomNum.o

请注意,因为您遇到了编译问题,所以我没有调用trunk,所以事情会更简单(即,它与您遇到的问题无关)。此外,我将main.cpp重命名为rand.cpp[再次,应该没有区别]

如果您使用公共成员vector::at函数,该函数返回向量中i位置的元素,那么您的代码将工作。。。

int main()
{
    RandomNum rand(5, 5, 100, 1000); // <----error  
    vector<float>* p = rand.getVecPointer();
    for (int i = 0; i < p->size(); i++) {
        cout << (p)->at(i);
    }
    return 0;
}

尽管这是一个有效的程序,但使用指针到矢量的理由很少。向量的构建是为了使用资源获取即初始化(RAII),这是一种管理其自身内存的方法。当你使用指针到矢量时,你就违背了RAII的目的。您可能需要处理内存分配/清理、空指针等问题,这正是RAII应该让您省去的。

getVecPointer()函数可以返回vector::data公共成员函数,该函数返回指向向量内部使用的数组中第一个元素的指针。。。

int* p = myvector.data();