我有两个源代码。第一个代码使用iostream
,第二个代码使用fstream
,但第二个代码有以下错误:
这是第一个源代码
#include<fstream>
#include<iostream>
#include<string>
using namespace std;
class Reactangle
{
protected:
float a, b;
public:
virtual void input(istream& inDevice)
{
cout << "Nhap chieu dai: ";
inDevice >> a;
cout << "Nhap chieu rong: ";
inDevice >> b;
}
};
class Square : public Reactangle
{
public:
void input(istream& inDevice)
{
cout << "Nhap canh";
inDevice >> a >> b;
}
};
void main()
{
Square *Test = new Square;
Test->input(cin);
system("pause");
}
这是第二个源代码(错误)
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
#pragma once
class CCatalogue
{
protected:
string m_ID;
string m_Title;
string m_Author;
int m_Count;
public:
/*int input(fstream f, int Pos)
{
f.open("Input.txt", ios::in);
f.seekg(Pos);
f >> *this;
}*/
friend fstream& operator>>(fstream& f, CCatalogue &List);
};
fstream& operator>>(fstream& f, CCatalogue &List)
{
//Read ID
f >> List.m_ID;
//Read title
getline(f, List.m_Title);
//Read author
getline(f, List.m_Author);
//Read amount of borrow
f >> List.m_Count;
return f;
}
class CBook : public CCatalogue
{
private:
string m_Publisher;
int m_Version;
string m_Year;
public:
int input(fstream f, int Pos)
{
f.open("Input.txt", ios::in);
f.seekg(Pos);
f >> *this;
}
friend fstream& operator>>(fstream& f, CBook &Book);
};
fstream& operator>>(fstream& f, CBook &Book)
{
//Read ID
f >> Book.m_ID;
//Read title
getline(f, Book.m_Title);
//Read author
getline(f, Book.m_Author);
//Read amount of borrow
f >> Book.m_Count;
//Read the publisher
getline(f, Book.m_Publisher);
//Read the version
f >> Book.m_Version;
//Read the year
getline(f, Book.m_Year);
return f;
}
int main()
{
fstream f;
int Pos=0;
CBook *Temp = new CBook();
Temp->input(f, Pos);
}
答案 0 :(得分:0)
basic_ios
复制构造函数是私有的,因此您不会意外复制流对象。就像将值传递给函数一样......
在现代代码中,复制构造函数和赋值运算符可能会被删除(= delete
),但该选项在C ++ 98中不可用。
答案 1 :(得分:0)
对于函数input()
,您尝试复制std::fstream
。无法复制流(但错误消息相当糟糕;希望实现将更新并获得= delete
d复制构造函数)。您需要通过引用传递参数。
请注意,即使您编写了程序,也很可能无法工作:在格式化输入(即in >> value
)和未格式化输入(例如std::getline(in, value)
)之间切换时,您通常会需要跳过前导空格。一个简单的方法是使用in >> std::ws
。
已经指出,除非你绝对需要,否则你应该不使用new
分配对象。如果您使用new
分配对象,则必须必须使用delete
正确释放它们。