用指针数组重载输入操作符
Overloading the input operator with an array of pointers
对于一个类项目,我有一个2D指针数组。我理解构造函数,析构函数等,但我有问题理解如何设置数组中的值。我们使用了重载输入操作符来输入值。到目前为止,我为这个操作符编写的代码是:
istream& operator>>(istream& input, Matrix& matrix)
{
bool inputCheck = false;
int cols;
while(inputCheck == false)
{
cout << "Input Matrix: Enter # rows and # columns:" << endl;
input >> matrix.mRows >> cols;
matrix.mCols = cols/2;
//checking for invalid input
if(matrix.mRows <= 0 || cols <= 0)
{
cout << "Input was invalid. Try using integers." << endl;
inputCheck = false;
}
else
{
inputCheck = true;
}
input.clear();
input.ignore(80, 'n');
}
if(inputCheck = true)
{
cout << "Input the matrix:" << endl;
for(int i=0;i< matrix.mRows;i++)
{
Complex newComplex;
input >> newComplex;
matrix.complexArray[i] = newComplex; //this line
}
}
return input;
}
显然,我这里的赋值语句是不正确的,但我不确定它应该如何工作。如果有必要包含更多代码,请告诉我。主构造函数是这样的:
Matrix::Matrix(int r, int c)
{
if(r>0 && c>0)
{
mRows = r;
mCols = c;
}
else
{
mRows = 0;
mCols = 0;
}
if(mRows < MAX_ROWS && mCols < MAX_COLUMNS)
{
complexArray= new compArrayPtr[mRows];
for(int i=0;i<mRows;i++)
{
complexArray[i] = new Complex[mCols];
}
}
}
这里是Matrix.h所以你可以看到属性:
class Matrix
{
friend istream& operator>>(istream&, Matrix&);
friend ostream& operator<<(ostream&, const Matrix&);
private:
int mRows;
int mCols;
static const int MAX_ROWS = 10;
static const int MAX_COLUMNS = 15;
//type is a pointer to an int type
typedef Complex* compArrayPtr;
//an array of pointers to int type
compArrayPtr *complexArray;
public:
Matrix(int=0,int=0);
Matrix(Complex&);
~Matrix();
Matrix(Matrix&);
};
#endif
我得到的错误是"不能将Complex转换为矩阵::compArrayPtr(又名Complex*)在分配"如果有人能解释我做错了什么,我会非常感激。
您的newComplex
是Complex
类型的对象(值),您试图将其分配给Complex*
指针。
要做到这一点,你应该动态地构造一个complex:
Complex* newComplex = new Complex();
input >> *newComplex;
matrix.complexArray[i] = newComplex;
但是要注意动态分配带来的所有后果(内存管理、所有权、共享状态…)
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 读取文件并输入到矢量中
- C++如何通过用户输入删除列表元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 用户定义函数中的指针和输入
- 如何在C++中检查2D数组中负值的输入验证
- 如何只允许用户输入正整数
- c++在输入和使用操作符中查找字符串
- c++操作符,用于a = b .* C,并将指向a、b和C对象的指针作为输入
- 用指针数组重载输入操作符
- 输入/输出操作符的优先级