无法将push_back()自定义类型转换为向量

时间:2016-04-24 02:24:28

标签: c++ vector

我正在尝试使用上述函数将我创建的Point类型对象push_back到一个向量中,但是在打印元素时我一直得到错误的值。 实际上,目的是从名为“src.txt”的源文件中获取一系列值,并使用排列值来组成vector<Point> v。 我确定这只是一个简单的修复,但我找不到它! 请在矢量声明后检查评论部分wright。 任何帮助将不胜感激。

我有一个Point类:

point.h

class Point {
public:

    Point();
    Point(int x, int y);
    int getX() {return this->x;}
    int getY() {return this->y;}
private:
    int x;
    int y;
};

point.cpp

#include "point.h"

Point::Point() 
    :x{0},
     y{0}
{}

Point::Point(int xx, int yy)
    :x{xx}, 
     y{yy}
{}

的main.cpp

#include <vector>
#include "point.h"
#include <iostream>
#include <fstream>

using namespace std;

ostream& operator << (ostream& os, Point& p);
istream& operator >> (istream& is, Point& p);
void init() {
    try {
        cout << "Source filename: ";
        string src;
        cin >> src; src += ".txt";
        ifstream file{src};
        if(!file) throw runtime_error("Could not open file...");

        vector<Point> v;
        Point p(5,6);
        cout << p;                   //displays x=5; y=6
        v.push_back(p);

        for(Point p : v) cout << p; //now it displays:
                                    //x=-2147193408; y=1


//        for(Point p; file >> p; ) v.push_back(p);
//        for(Point pp : v) cout << pp;

    }
    catch(exception& e) {
        cout << "Error: " << e.what() << endl;
    }
}

int main(int argc, char** argv) {
    init();
}
//output point operator
ostream& operator << (ostream& os, Point& p) {
    os << "x = " << p.getX() << "\n" << "y = " << p.getY();
    return os;
}
//input point operator
istream& operator >> (istream& is, Point& p) {
    int x, y;
    char ch1, ch2, ch3;
    is >> ch1 >> x >> ch2 >> y >> ch3;
    if(!is) return is;
    if(ch1 != '(' || ch2 != ',' || ch3 != ')') {
        is.clear(ios_base::failbit);
        throw runtime_error("bad");
        return is;
    }
    p = Point(x,y);
    return is;
}

0 个答案:

没有答案
相关问题