【发布时间】:2012-02-27 13:57:07
【问题描述】:
我的“记录”构造函数如下所示:
#include "Record.h" //both these headers #include <iostream>
#include "String.h"
Record :: Record(std::ifstream& is)
{
std :: istream & iss = static_cast<std::istream &>(is);
iss >> ID >> medium >> rating;
getline(iss, title);
if (!iss.good())
throw Record_exception(invalid_data);
}
其中 ID 是 int,medium 和 title 是用户定义的字符串类型(不是标准字符串),其中 operator>> 、 getline 和 operator
#include "String.h"
ostream& operator << (ostream& os, const String & s)
{
int str_length = s.size();
for (int i = 0; i < str_length ; i++)
os << s[i];
return os;
}
istream& operator >> (istream& is, String& str)
{
char input;
bool string_end = false;
int length = 0;
str.clear();
while (!string_end){
is.get(input);
if (!isspace(input) && is){
length++;
str +=input;
}else if (length || !is)
string_end = true;
}
return is;
}
istream& getline(std::istream& is, String& str)
{
char input;
bool string_end = false;
int length = 0;
str.clear();
while (!string_end){
is.get(input);
if (!isspace(input) && is){
length++;
str +=input;
}else if ((length && is.peek() == '\0') || !is)
string_end = true;
}
return is;
}
我将 ifstream 静态转换为 istream,因为我意识到编译器不接受我的“getline”和 operator
我的编译器错误现在包括:
“Record.cpp:在构造函数‘Record::Record(std::ifstream&)’中: Record.cpp:26:错误:类型无效的 static_cast 'std::basic_ifstream >' 输入 ‘std::istream&’
我在 red_hat linux 机器上使用标志“g++ -c -pedantic -Wall -fno-elide-constructors”进行编译
【问题讨论】:
-
你的构造函数应该只接受
istream&。 -
我们需要构造函数调用。此外,所有这些样板代码真的有必要吗? sscce.org
-
@KerrekSB,是的,如果我写了接口,我会这样做,但我没有,并且对应的构造函数声明不能更改。我只需要定义函数。
-
@sscce.org-Xeo ,我什至没有在任何主要的地方调用过构造函数。我不能用 -c 编译它,我和我的教授讨论了这两个函数的冗长性质,但同样,我们的导师要求两个具体任务并遵守他的指导方针,如果请专注于手头的问题而不是风格
-
@Leila:嗯,sscce.org 是一个链接。另外,我相当确定
operator<<、operator>>和getline在此处不需要来显示您的错误。这与“风格”无关。你甚至从未在这些函数中提及Record。
标签: c++ constructor inputstream filestream