【发布时间】:2021-04-04 07:13:24
【问题描述】:
我有一个关于我的构造函数不能正常工作的问题。每当我运行程序时,我的重载运算符可能无法正确执行,因为当我使用 cout 获得输出时,我总是得到默认的构造函数值。
我相信我的构造函数声明做得很好,但是我的所有对象都被 0 和 Unknown
这是我的 txt 文件:
1 Prince Heins 25
2 Lady Bridgette 29
3 Tony Ann 223
4 Lucy Phoenix 35
这是我的代码;
#include <iostream>
#include <string>
#include <conio.h>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <sstream>
#include <istream>
#include <iomanip>
#include <cstring>
#include <ostream>
using namespace std;
class contact{
private:
int listno;
string name;
string surname;
string phonenumber;
public:
contact(){
this->name="Unknown";
this->surname="Unknown";
this->phonenumber="Unknown";
this->listno=0;
}
contact (string name,string surname,string phonenumber){
this->name=name;
this->surname=surname;
this->phonenumber=phonenumber;
}
contact(int listno,string name,string surname,string phonenumber){
this->name=name;
this->surname=surname;
this->listno=listno;
this->phonenumber=phonenumber;
}
friend ostream & operator<< (ostream &out, const contact &con){
out << con.listno << con.name << con.surname << con.phonenumber;
return out;
}
friend istream & operator>> (istream &in, contact &con){
in >> con.listno >> con.name >> con.surname >> con.phonenumber;
return in;
}
};
int main(){
ifstream pbin("phoneData2.txt");
string line;
long linecount;
for(linecount=0;getline(pbin,line);linecount++);
contact* myArray = new contact[linecount];
pbin.seekg(0);
if(pbin.is_open()){
int i;
for(i=0;i<linecount;i++){
if(pbin!=NULL){
while(pbin>>myArray[i]);
}
}
pbin.close();
cout << myArray[2]; // try attempt
return 0;
}
}
这是我对 cout 的输出
【问题讨论】:
-
您错过了将文件的读取指针重置为第一个之后的开头。环形。另外你不需要提前知道行数,只需使用
std::getline()和std::istringstream根据需要提取值。 -
在第一个循环之后,
pbin仍然设置了eof标志。所有读取操作都失败。事实上,我认为if(pbin!=NULL)检查是错误的,所以代码甚至没有调用你的operator>> -
使用调试器。
-
请不要在此处发布文字图片。您可以轻松复制终端输出。
-
@πάνταῥεῖ 我怎样才能重置读取指针,你能更具体一点吗?感谢您提供有关 istringstream 的信息!我不知道=)
标签: c++ class oop object overloading