将外部变量传递给类 c++

Passing outside variable to a class c++

本文关键字:c++ 外部 变量      更新时间:2023-10-16

我在这里放了一个简化版本的代码。我试图做的是从输入文件中读取每一行并将其存储在类"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