CodeBlocks编译器问题,C++
CodeBlocks compiler issue, C++
我在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();
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 使用mongocxx驱动程序时包含头文件问题