C++提取器 (>>) 重载不读取和分配矩阵类

C++ extractor (>>) overload not reading and assigning Matrix class

本文关键字:gt 分配 读取 提取 C++ 重载      更新时间:2023-10-16

对于学校,我们应该承担教师的主要功能,并围绕它构建实现;他的文件打开如下文件:

int main(int argc, char *argv[])
{
ifstream infile;
string infilename;
Matrix w;
infile.open(argv[1]);
    if(!infile.is_open()) {
        cerr << "ERROR opening input file " << argv[1] << endl;
        cerr << "Usage: Prog1 <input file name> <output file name>n";
        return(0);
        }
infile >> w;

我们应该将矩阵类定义为:

class Matrix{
private:
    //these are given and not allowed to change
    double tl;
    double tr;
    double bl;
    double br;
public:

    //this is all me, 
    Matrix(); //basic constructor
    Matrix(double intl, double intr, double inbl, double inbr); // advanced constructor
    void print();
    void assign(double intl, double intr, double inbl, double inbr); //
    friend Matrix operator+(const Matrix& x, const Matrix& y);
    friend Matrix operator-(const Matrix& x, const Matrix& y);
    friend Matrix operator*(const Matrix& x, const Matrix& y);
    friend Matrix operator/(const Matrix& x, const Matrix& y);
    Matrix& operator=(const Matrix& matrix);
    friend ostream& operator<< (ostream &out, const Matrix& y);
    //PROBLEM AREA? ///////////////////////////////////////////////////
    friend istream& operator>> (istream &in, Matrix w);
protected:
};

所以当需要读取输入文件时,我应该如何从main将数字读取到w中?我现在拥有的是:

istream& operator >> (istream &in, Matrix w){
    in >> w.tl >> w.tr >> w.bl >> w.br;
    cout << w;
    return in;
}

这会产生错误,因为w.tl是私有的,我在它公开的时候对它进行了测试,但它仍然没有读取任何内容。我测试的只是将数字读取为正常的双值,这些值读取得很好,但我必须使用>>运算符进行内联读取和赋值,该运算符必须返回&在中,所以我不能使用.assign()函数将我读取的doubles放入矩阵中,并将该矩阵传递回main。

我该如何处理?有没有可能让>>运算符超负荷执行我教授的要求?

缺少引用,即Matrix w应为Matrix & w:

取而代之的是:

 istream& operator>> (istream &in, Matrix w);

你应该有:

 istream& operator>> (istream &in, Matrix & w);

很高兴我能帮忙。