我在这里放置了代码的简化版本。我想做的是从输入文件中读取每一行,并将其存储在“ fifo”类中。但是,在每个商店之前,我都尝试打印我以前的fifo值(这是用于调试)。我看到的是,即使在调用fifo.add函数之前,先前的值也已被覆盖。 getline函数本身正在自行覆盖fifo。有人可以告诉我这是怎么回事吗?

//fifo.h

#ifndef FIFO_H_
#define FIFO_H_

class fifo {
        private:
                char* instr_arr;
                int head;
                int tail;
        public:
                fifo();
                fifo(int,int);
                void add(char*);
                void print_instruction(void);
};

#endif

//fifo.cpp

#include "fifo.h"
#include <iostream>
//using namespace std;

fifo::fifo() {
        head = 0;
        tail = 0;
        instr_arr = "NULL";
}

fifo::fifo(int h, int t) {
        head = h;
        tail = t;
}

void fifo::add (char *instr) {
        instr_arr = instr;
}

void fifo::print_instruction (void) {
        std::cout << instr_arr << std::endl;
}

//code.cpp

#include <iostream>
using namespace std;
#include <fstream>
using namespace std;
#include "fifo.h"

#define MAX_CHARS_INLINE 250

int main (int argc, char *argv[]) {
        char buf[MAX_CHARS_INLINE];     //Character buffer for storing line
        fifo instruction_fifo;          //FIFO which stores 5 most recent instructions

        const char *filename = argv[1];
        ifstream fin;
        fin.open(filename);

        while(!fin.eof()) {
                std::cout << buf << std::endl;
                fin.getline(buf, MAX_CHARS_INLINE);
                instruction_fifo.print_instruction();  //This instruction prints the line which was read from getline above!! Why??
                instruction_fifo.add(buf);
                }
        return 0;
}

最佳答案

您实际上并没有将数据存储在FIFO(或FIFO管理的存储块)中,而只是将指针(指向buf)存储。

打印instr_arr时,基本上是在打印buf,因为instr_arr指向buf

关于c++ - 将外部变量传递给类C++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21950840/

10-16 05:02