Error while overloading insertion operator [duplicate] - c++

This question already has answers here:
My attempt at value initialization is interpreted as a function declaration, and why doesn't A a(()); solve it?
(5 answers)
Understanding 'most vexing parse' - why allow ambiguous syntax?
(2 answers)
Closed 5 years ago.
I have following piece of code
#include <iostream>
using namespace std;
class TestMatrix {
int row, col;
int **arr = NULL;
public:
friend istream& operator>> (istream &in, TestMatrix &mat);
friend ostream& operator<< (ostream &out, TestMatrix &mat);
TestMatrix(int row=1, int col=1):row(row), col(col){
arr = new int*[row];
for (int i = 0; i<row; i++) {
arr[i] = new int[col];
}
}
};
TestMatrix() {
/*cout << "Enter number of rows of your matrix";
cin >> this->row;
cout << "Enter number of columns of matrix";
cin >> this->col;*/
this->row = 3;
this->col = 3;
arr = new int*[this->row];
for (int i = 0; i<this->row; i++) {
arr[i] = new int[this->col];
}
}
istream & operator>> (istream & in, TestMatrix &mat)
{
cout << "Enter " << mat.row * mat.col << " numbers row wise \n";
for (int i = 0; i < mat.row; i++) {
for (int j = 0; j < mat.col; j++) {
in >> mat.arr[i][j];
}
}
return in;
}
ostream & operator<< (ostream & out, TestMatrix &mat) {
for (int i = 0; i < mat.row; i++) {
for (int j = 0; j < mat.col; j++) {
cout << mat.arr[i][j] << " ";
}
cout << "\n";
}
return out;
}
int main() {
TestMatrix mMatrix1(3, 3);
TestMatrix mMatrix2();
//**This works fine
cin >> mMatrix1;
//**This gives error
cin >> mMatrix2;
return 0;
}
I am trying to overload insertion and extraction operator.
I have instantiated class TestMatrix using overloaded constructors.
While trying to access overloaded operator with instance which was constructed using constructor without argument, I get error stating
binary '>>': no operator found which takes a right-hand operand of type 'overloaded-function' (or there is no acceptable conversion)
Can someone please explain reason for same.

Related

I can enter the inputs but I'm not able to see the output when I run my code (CTRL+F5) in C++ in visual studio 2017

I can enter the inputs but I'm not able to see the output when I run my code (CTRL+F5) in C++ in visual studio 2017. This code is written to overload the operator *, ">>" & "<<" through the friend functions. one constructor initializes the vector elements to zero while the other constructor is used to initialize the elements of vector through the array.
My code is as below:
//vector.h
#pragma once
const int SIZE = 3;
#include<iostream>
using namespace std;
class vector
{
int v[SIZE];
public:
vector();
vector(int *x);
friend vector operator *(vector a, int b);
friend vector operator *(int b,vector a);
friend istream & operator >>(istream &input, vector &x);
friend ostream & operator <<(ostream &output, vector &y);
};
//vector.cpp
#include "vector.h"
#include<iostream>
using namespace std;
vector::vector()
{
for (int i = 0; i < SIZE; i++)
v[i] = 0;
}
vector::vector(int *x)
{
for (int i = 0; i < SIZE; i++)
v[i] = x[i];
}
vector operator *(vector a, int b) {
vector temp;
for (int i = 0; i < SIZE; i++)
temp.v[i] = a.v[i]*b;
return temp;
}
vector operator *(int a, vector b) {
vector temp;
for (int i = 0; i < SIZE; i++)
temp.v[i] = a * b.v[i];
return temp;
}
istream & operator >>(istream &input, vector &x) {
for (int i = 0; i < SIZE; i++)
input >> x.v[i];
return (input);
}
ostream & operator <<(ostream &output, vector &y) {
output << "(" << y.v[0];
for (int i = 1; i < SIZE; i++)
output <<","<< y.v[i];
output << ")";
return (output);
}
//main.cpp
#include "vector.h"
#include<iostream>
using namespace std;
int x[SIZE] = { 2,4,6 };
int main() {
vector m;
vector v2 = x;
cout << "Enter the elements of vector m:" << "\n";
cin >> m;
cout << "\n";
vector m1, m2;
m1 = m * 2;
m2 = 2 * v2;
cout << "m= "<<m<<"\n";
cout << "\n";
cout << "m1= " << m1 << "\n";
cout << "m2= " << m2 << "\n";
cin.get();
return 0;
}
Probably your linker settings are incorrect. Go to menu item Project/Properties. Then in the dialog find Configuration Properties/Linker/System/Subsystem and make sure it says Console (/SUBSYSTEM:CONSOLE).
Evgeny is correct cin.get() is not guaranteed to halt your program because there are still characters waiting to be read from cin that are left over from previous reads.
Your code assumes you must enter 3 number. If you enter less numbers you see no output.
Some comments:
Your cin.get() doesn't stop execution.
Using std (like using namespace std) and definition own vector class - it's very bad idea.

Using 2 overloaded operators in one command cause an error

I was creating a matrix class with overloaded operators in C++, I overloaded operators, << (output, with the ostream library), operator + that adds to matrices, operator = that's is used to assign one matrix to another. The problem is that when I use
cout<<m1+m2<<endl;
I get an error
E0349: No operator << matches these operands type are: std::ostream << Matrix
But if i do the following:
Matrix m = m1 + m2;
cout<<m<<endl;
it works perfect.
Here is the << operator:
ostream& operator<< (ostream &os,const Matrix& m)
{
if (m.isValid())
{
os << '|';
for (int i = 0; i < m.getRows(); i++)
{
for (int j = 0; j < m.getCols(); j++)
{
os << m.getMatrix()[i][j];
if (j < m.getCols() - 1)
{
os << ',';
}
}
os << '|';
}
}
else
{
os << "invalid matrix!";
}
return os;
}
The + operator:
Matrix Matrix::operator+ (Matrix &m)
{
Matrix* answer = new Matrix(m); //allocating space
if (valid && m.valid)//if they are both valid
{
if (colNum == m.colNum&&rowNum == m.rowNum) //if are from same size
{
answer->valid = true; //valid set to be true
for (int i = 0; i < rowNum; i++) //going over the matrix
{
for (int j = 0; j < colNum; j++)
{
answer->matrix[i][j] += matrix[i][j]; //adding data
}
}
}
else
{
//clearing data
delete answer;
answer = new Matrix();
}
}
else
{
//clearing data
delete answer;
answer = new Matrix();
}
return *answer;
}
And the = operator:
Matrix Matrix::operator= (Matrix &m)
{
int rows = m.rowNum; //putting cols and rows from the data
int cols = m.colNum;
if (m.valid)
{
matrix = new int*[rows]; //defining the matrix - first allocatin space for rows
for (int i = 0; i < rows; i++) //now allocating space for cols
{
matrix[i] = new int[cols];
}
for (int i = 0; i < rows; i++) //now going over the matrix and putting the data in
{
for (int j = 0; j < cols; j++)
{
matrix[i][j] = m.matrix[i][j];
}
}
}
//putting the rows and cols data
rowNum = m.rowNum;
colNum = m.colNum;
valid = m.valid; //setting to the right valid type
return *this;
}
and the class variables:
class Matrix
{
private:
bool valid;
int** matrix;
int rowNum;
int colNum;
There is a copy constructor a string constructor and a constructor that gets string input according to an algorithm and transforms it to a matrix.
You are actually faced with the fact that you Can't pass temporary object as reference (the link is to another question here on StackOverflow).
The solution in your case should be to replace:
ostream& operator<< (ostream &os,Matrix& m)
with:
ostream& operator<< (ostream &os,const Matrix& m)
as the overloaded operator signature. You currently expects an lvalue reference, In the case of
Matrix m = m1 + m2;
cout << m << endl;
that is what you're calling the function with m - a named variable and will outlive the execution of the command. In the failing case, you're calling the function with m1+m2 - the result of a plus operation, which is a temporary object. It just doesn't match your overload.
By the way - this change also makes sense because you're not modifying the matrix as you print it - you treat it as const.

C++ Subscript operator

I have written a code but it doesn't seems to work. Every time I execute the program, I get this error
Run-Time Check Failure #2 - Stack around the variable 'ary' was
corrupted
anyway here is my code(it is a small code)
#include <iostream>
using namespace std;
class Arrayz{
private:
int arry[5];
public:
Arrayz(){}
void setInf(){
for(int i = 0; i < 5; ++i){
cout << "Enter age of your friends: ";
cin >> arry[5];
}
}
const int& operator [](const int pos){
return arry[pos];
}
};
int main(){
Arrayz ary;
ary.setInf();
cout << "Here are your friend's age: " << endl;
for (int i = 0; i < 5; ++i){
cout << ary[i] << endl;
}
return 0;
}
also can you also help in subscript operator, I just don't seem to understand how to declare and use them. Also it seems pretty foolish to write a program without first understanding it first but anyway help would be appreciated :)
You probably mean cin >> arry[i]; – i, not 5.
You made a typo in member function setInf. Instead of cin >> arry[5]; there shall be cin >> arry[i];
void setInf(){
for(int i = 0; i < 5; ++i){
cout << "Enter age of your friends: ";
cin >> arry[i];
}
}
As for the subscript operator then you defined it correctly
const int& operator [](const int pos){
return arry[pos];
}
though there is no need to declare the parameter with qualifier const. Also the operator itself should have qualifier const You could write simply
const int& operator [](int pos) const {
return arry[pos];
}
Or
int operator [](int pos) const {
return arry[pos];
}
Also you could define its non-const version when the user could change elements of the array arry.
int & operator []( int pos) {
return arry[pos];
}
Also it is a good idea that your class had a member function that would return the size of the array. For example
class Arrayz{
private:
static const size_t N = 5;
int arry[N];
public:
Arrayz(){}
void setInf(){
for(int i = 0; i < N; ++i){
cout << "Enter age of your friends: ";
cin >> arry[i];
}
}
int operator [](int pos) const {
return arry[pos];
}
int & operator []( int pos) {
return arry[pos];
}
size_t size() const { return N; }
};
And in main you could write
for (int i = 0; i < ary.size(); ++i){
cout << ary[i] << endl;
}

C++ assignment operators dynamic arrays

First off i know the multiplying part is wrong but i have some questions about the code.
1. When i am overloading my operator+ i print out the matrix using cout << *this then right after i return *this and when i do a+b on matix a and matix b it doesnt give me the same thing this is very confusing.
2. When i make matrix c down in my main i cant use my default constructor for some reason because when i go to set it = using my assignment operator overloaded function it gives me an error saying "expression must be a modifiable value. although using my constructor that sets the row and column numbers is the same as my default constructor using (0,0).
3. My assignment operator= function uses a copy constructor to make a new matrix using the values on the right hand side of the equal sign and when i print out c it doesn't give me anything
Any help would be great this is my hw for a algorithm class which i still need to do the algorithm for the multiplying matrices but i need to solve these issues first and im having a lot of trouble please help.
//Programmer: Eric Oudin
//Date: 10/21/2013
//Description: Working with matricies
#include <iostream>
using namespace std;
class matrixType
{
public:
friend ostream& operator<<(ostream&, const matrixType&);
const matrixType& operator*(const matrixType&);
matrixType& operator+(const matrixType&);
matrixType& operator-(const matrixType&);
const matrixType& operator=(const matrixType&);
void fillMatrix();
matrixType();
matrixType(int, int);
matrixType(const matrixType&);
~matrixType();
private:
int **matrix;
int rowSize;
int columnSize;
};
ostream& operator<< (ostream& osObject, const matrixType& matrix)
{
osObject << endl;
for (int i=0;i<matrix.rowSize;i++)
{
for (int j=0;j<matrix.columnSize;j++)
{
osObject << matrix.matrix[i][j] <<", ";
}
osObject << endl;
}
return osObject;
}
const matrixType& matrixType::operator=(const matrixType& matrixRight)
{
matrixType temp(matrixRight);
cout << temp;
return temp;
}
const matrixType& matrixType::operator*(const matrixType& matrixRight)
{
matrixType temp(rowSize*matrixRight.columnSize, columnSize*matrixRight.rowSize);
if(rowSize == matrixRight.columnSize)
{
for (int i=0;i<rowSize;i++)
{
for (int j=0;j<columnSize;j++)
{
temp.matrix[i][j] = matrix[i][j] * matrixRight.matrix[i][j];
}
}
}
else
{
cout << "Cannot multiply matricies that have different size rows from the others columns." << endl;
}
return temp;
}
matrixType& matrixType::operator+(const matrixType& matrixRight)
{
matrixType temp;
if(rowSize == matrixRight.rowSize && columnSize == matrixRight.columnSize)
{
temp.setRowsColumns(rowSize, columnSize);
for (int i=0;i<rowSize;i++)
{
for (int j=0;j<columnSize;j++)
{
temp.matrix[i][j] = matrix[i][j] + matrixRight.matrix[i][j];
}
}
}
else
{
cout << "Cannot add matricies that are different sizes." << endl;
}
return temp;
}
matrixType& matrixType::operator-(const matrixType& matrixRight)
{
matrixType temp(rowSize, columnSize);
if(rowSize == matrixRight.rowSize && columnSize == matrixRight.columnSize)
{
for (int i=0;i<rowSize;i++)
{
for (int j=0;j<columnSize;j++)
{
matrix[i][j] -= matrixRight.matrix[i][j];
}
}
}
else
{
cout << "Cannot subtract matricies that are different sizes." << endl;
}
return *this;
}
void matrixType::fillMatrix()
{
for (int i=0;i<rowSize;i++)
{
for (int j=0;j<columnSize;j++)
{
cout << "Enter the matix number at (" << i << "," << j << "):";
cin >> matrix[i][j];
}
}
}
matrixType::matrixType()
{
rowSize=0;
columnSize=0;
matrix = new int*[rowSize];
for (int i=0; i < rowSize; i++)
{
matrix[i] = new int[columnSize];
}
}
matrixType::matrixType(int setRows, int setColumns)
{
rowSize=setRows;
columnSize=setColumns;
matrix = new int*[rowSize];
for (int i=0; i < rowSize; i++)
{
matrix[i] = new int[columnSize];
}
}
matrixType::matrixType(const matrixType& otherMatrix)
{
rowSize=otherMatrix.rowSize;
columnSize=otherMatrix.columnSize;
matrix = new int*[rowSize];
for (int i = 0; i < rowSize; i++)
{
matrix[i]=new int[columnSize];
for (int j = 0; j < columnSize; j++)
{
matrix[i][j]=otherMatrix.matrix[i][j];
}
}
}
matrixType::~matrixType()
{
delete [] matrix;
}
int main()
{
matrixType a(2,2);
matrixType b(2,2);
matrixType c(0,0);
cout << "fill matrix a:"<< endl;;
a.fillMatrix();
cout << "fill matrix b:"<< endl;;
b.fillMatrix();
cout << a;
cout << b;
//c = a+b;
cout <<"matrix a + matrix b =" << a+b;
system("PAUSE");
return 0;
}
EDIT:
still having trouble with things not returning what i am telling it to return
This code doesn't do what you think it does:
for (int j = 0; j < columnSize; j++)
{
matrix[i]=new int[columnSize];
matrix[i][j]=otherMatrix.matrix[i][j];
}
It allocates a column, then copies the first value. Then it allocates another column (forgetting about the old column), and copies the second value. Then it allocates another column (forgetting about the old column again), and copies the third value.
I hope the problem is clear from that description alone.
Are you trying to use matrixType c();? That would declare a function. The correct syntax to use the default constructor would be matrixType c;
Your operator= doesn't actually assign anything. So c = a+b; calculates a+b but doesn't change c.

Trouble overloading operator >> for a matrix class

I am trying to learn operator overloading by working on overloading >> for a matrix class to enable the key-board based input for a matrix by calling sth such as
Matrix M1;
cin >> M1;
The operator overloading part is given in the following
istream &operator>>(istream &in, Matrix &m)
{
for (int i = 0; i < m.dx; ++i) {
for (int j = 0; j < m.dy; ++j)
in >> m.p[i][j];
}
return in;
}
It turns work that my implementation was not correct at all. Can you let me know why this implementation is wrong?
I implemented the above part by imitating an existing implementation of overloading >>, which has been proven to work fine in the matrix output part, like cout<< A; where A is a matrix
ostream &operator<<(ostream &out, const Matrix &m)
{
for (int i = 0; i < m.dx; ++i) {
for (int j = 0; j < m.dy; ++j)
out << m.p[i][j] << " ";
out << endl;
}
return out;
}
I believe that the problem with your operator >> is that you're using whatever dimensions already happen to be in the Matrix rather than trying to recover the dimensions from the input that you find.
I think that your best bet would be to have the operator << implementation preface the matrix with dimension information (such as the number of rows and columns) and then have the operator >> function read in that information. For example:
ostream &operator<<(ostream &out, const Matrix &m)
{
out << m.dx << ' ' << out.dy << '\n';
for (int i = 0; i < m.dx; ++i) {
for (int j = 0; j < m.dy; ++j)
out << m.p[i][j] << " ";
out << endl;
}
return out;
}
With this in hand, you can write your stream extraction operator as
istream &operator>>(istream &in, Matrix &m)
{
in >> m.dx >> m.dy;
/* Some sort of logic to ensure that you've allocated an array large enough to
* hold all the elements ...
*/
for (int i = 0; i < m.dx; ++i) {
for (int j = 0; j < m.dy; ++j)
in >> m.p[i][j];
}
return in;
}
This may not be the most aesthetically pleasing input and output operators, but they should get the job done.
If you want to make these operators a bit classier, consider outputting the elements of the matrix using some special character to delimit rows and columns. For example, you might try outputting the matrix
0 1 2
3 4 5
6 7 8
as
[[0 1 2][3 4 5][6 7 8]]
With this setup, the size information about the matrix is implicit in how the bracket grouping works. Then again, this may make it a bit trickier to read the input, since you wouldn't know in advance how large the matrix is. But go with what's easiest for yourself overall.
As an FYI, you probably don't want to use endl to delimit lines when writing a stream insertion operator. In addition to writing a newline, endl flushes the buffer. If your stream is hooked up to a network connection, you may not want to keep flushing the buffer whenever you have a new line of the matrix, since that could result in a lot of data getting sent in bursts (slow) rather than grouping it all together at once (fast).
Hope this helps!
I don't think your code is wrong particularly.
If pressed I would suggest checking the stream condition in the loop.
For your information, the following code worked when I tested:
struct Matrix {
static int const dx = 2, dy = 2;
int p[ dx ][ dy ];
};
istream &operator>>(istream &in, Matrix &m)
{
for (int i = 0; i < m.dx; ++i) {
for (int j = 0; j < m.dy; ++j)
if ( ! (in >> m.p[i][j]) ) return in;
}
return in;
}
int main() {
Matrix M1;
cin >> M1;
cout << M1;
}
Hope this helps
#include<iostream>
using namespace std;
class Array /*overload of subscript operator of 1D array*/
{
private: int *p;
public:
int length;
Array(int size = 0): length(size)
{
p=new int(length);
}
int& operator [](const int k)
{
return p[k];
}
};
class Matrix
{
private: Array *p;
public:
int r,c;
Matrix(int i=0, int j=0):r(i), c(j)
{
p= new Array[r];
}
Array& operator [](const int& i)
{
return p[i];
}
friend istream& operator >> (istream& in, Matrix& m);
/*friend ostream& operator << (ostream& out, Matrix& m);*/
};
istream& operator >> (istream& in, Matrix& m)
{
for(int i=0 ; i < m.r ; i++)
{
for(int j=0 ; j < m.c ; j++)
in >> m[i][j];
}
}
/*ostream& operator << (ostream& out, Matrix& m)
{
for(int i=0 ; i < m.r ; i++)
{
for(int j=0 ; j < m.c ; j++)
out << m[i][j] << " ";
out << endl;
}
}*/
/*Driver program*/
int main()
{
Matrix M1(3,3); /*for checking purpose*/
cin >> M1;
/*cout << "\n" << M1;*/
}