C++提取器 (>>) 重载不读取和分配矩阵类
C++ extractor (>>) overload not reading and assigning Matrix class
对于学校,我们应该承担教师的主要功能,并围绕它构建实现;他的文件打开如下文件:
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);
很高兴我能帮忙。
相关文章:
- 将数组的地址分配给变量并删除
- vector.resize()中的分配错误
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- Win32编译器选项和内存分配
- 函数中堆分配的效果与缺少堆分配的情况
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 获取字符串的长度并将其分配给数组
- 将地址分配给本地指针后,公共对象的变量将消失
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 有没有一种方法可以使用placement new将堆叠对象分配给分配的内存
- 我在二维向量中是否正确分配了内存
- 正在尝试重载二进制搜索树分配运算符
- GlobalAlloc而不是其他分配方法
- 自定义先决条件对移动分配运算符有效吗
- 我可以重新分配/覆盖std::字符串吗
- 在c++中使用动态分配的问题
- EASTL矢量<向量<int>>连续的
- 当一个新对象被分配到它的地址时,对象是否必须被销毁
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ