将外部变量传递给类 c++
Passing outside variable to a class c++
我在这里放了一个简化版本的代码。我试图做的是从输入文件中读取每一行并将其存储在类"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
。
相关文章:
- 在函数内部的声明中初始化数组,并在外部使用它
- 使外部项目可用于find_package CMake
- C++:Application.cpp中抛出了未解析的外部符号(解决方案在问题的末尾,供未来的读者参考)
- 使用外部SDK工具链文件在VisualStudio上生成项目编译错误
- C++:来自外部文件的Trivia
- 从函数角度看ID到文件路径的内部与外部映射
- C++:将外部库链接到dll库
- spdlog标头仅与外部fmt一起使用.spdlog错误:'内部':不是'fmt'
- 节俭并发:未解决的外部问题
- 如何在c++中从git建立外部库
- 未解析的外部符号_MsiLocateComponentW@12.
- 如何使用对C函数和类对象的外部调用来处理C++头文件
- 具有外部"c"和程序集的未定义函数
- 为什么导入Mixed native/CLR lib.dll的本机C++应用程序没有在Mixed lib.dll中的外部变
- 在C++中使用 gRPC 时未解析的外部符号
- 在类函数中初始化外部作用域变量
- 如果全局变量默认是外部变量,为什么要添加"extern"关键字?
- 调用外部函数,无法指定类型 C++/MVS
- 同时具有"外部"和"内联"说明符的变量
- LibPrivoxy: 未解析的外部符号 __declspec(dllimport) int __stdcall Sta