簡體   English   中英

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()

主程序

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

隨機數

#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

隨機數

#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

這是 make 的輸出:

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

請注意,因為您遇到了編譯問題,所以我沒有調用 trunc 調用,所以事情會更簡單(即它與您遇到的問題沒有密切關系)。 另外,我將 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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM