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

标签 c++ class operator-overloading overloading private

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

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;

我们应该将 Matrix 类定义为:

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 是私有(private)的,我在它公开时对其进行了测试,但它仍然没有读取任何内容。我测试只是将数字读入正常的 double 值,这些读得很好,但我必须使用 >> 运算符进行内联读取和分配,该运算符必须返回 &in,所以我不能使用 .assign() 函数将我读到的 double 放入矩阵中,然后将该矩阵传递回主矩阵。

我该如何处理这个问题?是否可以重载 >> 运算符来执行我的教授要求的操作?

最佳答案

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

而不是这个:

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

你应该有:

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

很高兴我能提供帮助。

关于C++ 提取器 (>>) 重载不读取和分配 Matrix 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26857169/

相关文章:

c++ - 无法将 “member pointer to derived class”转换为 “member pointer to base class”

c++ - 在 Mac OS X 中模拟按键事件

c++ - 在 C++ 中使公共(public)数据成员不可访问

java - MySQL 和 SQLite 类

Haskell - 添加类型类?

c++ - 在 C++ 中重载 ">>"和 "<<"

c++ - 具有多重继承的单例

静态库的c++链接器错误

c++ - 如何检查链表是否为空

java - 为什么 Java 不需要运算符重载?