带有指针的重载插入/提取运算符
Overloaded insertion/extraction operator with pointer
正在尝试执行简单的任务。打开 ifstream 以通过重载提取运算符从文本文件中读取。看起来不错,没有执行前错误。相信问题是由在此处使用指针引起的,但我没有看到问题。最后,我需要创建一个链表并使用重载的插入运算符输出到控制台。
使用Visual Studio。程序当前崩溃,出现以下异常: 引发异常:读取访问冲突。 这0xCCCCCCD0。
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
class Book {
public:
friend ostream& operator<< (ostream& out, Book* book) {
out << book->title_;
return out;
}
friend istream& operator>> (istream& in, Book* & book) {
getline(in, book->title_);
return in;
}
Book* setNext(Book* book) {
nextPtr_ = book;
return nextPtr_;
}
Book() : nextPtr_(NULL) {}
string getTitle() {
return title_;
}
Book* nextPtr_;
private:
string title_;
};
int main() {
ifstream inputFile;
Book *head;
inputFile.open("titles.txt");
// Creates head
head = new Book();
inputFile >> head;
Book* temp = head;
Book* newe;
for (int i = 0; i < 2; i++) {
inputFile >> newe;
cout << newe->getTitle();
temp->setNext(newe);
temp = temp->nextPtr_;
}
/*
for (int i = 0; i < 2; i++) {
cout << head << endl;
temp = head->nextPtr_;
}*/
system("PAUSE");
return 0;
}
为类实现流运算符的正确方法是通过引用而不是指针传递类对象:
class Book {
public:
friend ostream& operator<< (ostream& out, const Book &book) {
out << book.title_;
return out;
}
friend istream& operator>> (istream& in, Book &book) {
getline(in, book.title_);
return in;
}
...
string getTitle() const { return title_; }
...
};
然后在将Book*
指针传递给运算符时取消引用它们:
inputFile >> *head;
inputFile >> *newe;
cout << *newe;
cout << *head << endl;
至于你的崩溃,那是因为你的newe
指针在你传递给operator>>
时是未初始化的。您需要在每次循环迭代中创建一个新的Book
对象:
Book* newe;
for (int i = 0; i < 2; i++) {
newe = new Book; // <-- add this!
inputFile >> *newe;
...
}
相关文章:
- 在C++中使用重载提取运算符时出现问题
- 使用 istream 提取运算符进行 csv 解析:如何检测缺失的字段值?
- 将文本文件数据读入字符数组时提取运算符的歧义
- 派生类 插入和提取运算符重载以及基类与派生类之间的强制转换
- 长方程加法/减法计算器,从文本文件中提取运算符和数字
- 运算符重载流提取运算符 (>>) C++会导致无限递归流提取
- 无法在C++中过载流提取运算符 (>>)
- 带有指针的重载插入/提取运算符
- 防止为字符串流提取运算符不支持的类型实例化模板类 (>>)
- 为什么我不能对提取运算符进行 decltype
- 是否保证标准提取运算符>>在失败时不会更改参数?
- 提取运算符 (>>) 可以覆盖变量吗?
- 重载提取运算符
- C++ 重载提取运算符 - 无法访问类中声明的私有成员
- 如何在重载提取运算符中读取行(忽略空格字符)
- 如何在C++中重载模板的朋友提取运算符(>>)?
- 两个类的重载提取运算符
- 为什么 cin 提取运算符会导致段错误
- 在派生类中使用提取运算符(>>)的方法以及在C++中处理静态数据成员的方法
- 提取运算符是否删除分隔符