I have tried many ways to figure out this error, but still I am a beginner and can't figure it out.
I have done exactly as in my handout. We are required to show an output of a matrix but due to some error my program is getting stuck. It says that, e.g., star has not been declared in this scope. I have tried removing using namespace std;, and I have tried changing the header files but still no solution.
#include <iostream>
#include <stdlib.h>
#include <iomanip>
using namespace std;
class Matrix
{
private:
int numRows;
int numCols;
float elements[3][3];
public:
Matrix (int rows=0, int cols=0 )
{
numRows=rows;
numCols=cols;
}
friend ostream& operator<<(std::ostream&,Matrix&);
friend istream& operator>>(std::istream&,Matrix&);
friend ostream& spaceFirst(std::ostream&);
friend ostream& spaceBetween(std::ostream&);
friend ostream& line(std::ostream&);
friend ostream& newline( ostream&);
friend ostream& star(std::ostream &);
friend ostream& sound(std::ostream&);
};
istream&operator>>(istream&input, Matrix&m)
{
for (int i=0;i<m.numRows; i++)
{
for (int j=0;j,m.numCols;j++)
{
input>>m.elements[i][j];
}
}
return input;
}
//defining the operator<<
ostream&operator<<(std::ostream &output, Matrix&m)
{
for (int i=0;i<60; i++)
{
if(i==30)
{
output<<"Displaying th Matrix:";
}
else
{
output<<star;
}
}
output<<newline;
for(int r=0;r<m.numRows;r++)
{
output<<spacefirst<<line;
for (int c=0;c<m.numCols;c++)
{
output<<spaceBetween<<m.elements[r][c]<<sound<<spaceBetween;
}
output<<spaceBetween<<line;
output<<newline;
}
output<<newline;
return output;
}
ostream & spacefirst(std::ostream & output)
{
output<<setw(33);
return output;
}
std::ostream & spaceBetween(std::ostream & output)
{
output<<setw(4);
return output;
}
std::ostream & line(std::ostream & output)
{
output<<"|";
return output;
}
std::ostream & newline(std::ostream & output)
{
output<<endl;
return output;
}
std::ostream & star(std::ostream & output)
{
output<<"*";
return output;
}
std::ostream & sound(std::ostream & output)
{
output<<"\a";
return output;
}
int main()
{
Matrix matrix(3,3);
cin>>matrix;
cout<<matrix;
system("Pause");
return 0;
}
Friending those manipulators doesn't magically making the available in global namespace, and that's where they need to be for the friended free functions like
operator <<andoperator >>for your matrix class to access them.Foregoing the broken loop condition and obvious uncompilable misspelling of
spaceFirstvsspacefirst, put the following before any use (before the class itself is an obvious choice):Keep the friend declarations as well (although honestly, most/all of these don't need friending).
Alternatively, you can relocate the bare manipulators before any usage within the source file as well.
See it live here.