简体   繁体   中英

How can I use void printMatrix( ostream& os = cout ) const?

I am trying to learn C++, and I've got a task, to do some printing with this function, and I don't understand how to use the ostream. Can anyone help me please?

    void Matrix::printMatrix( ostream& os = cout ) const{
    for(int i=0; i<n; i++)
      for(int j=0; i<m; j++)
        os<<elements[i][j]<<"\n";
    }

I've tried to do this, but it threw me some errors, and I don't know how to handle this. The errors:

Matrix.cpp:47:48: error: default argument given for parameter 1 of 'void Matrix::printMatrix(std::ostream&) const' [-fpermissive] In file included from Matrix.cpp:8:0: Matrix.h:25:10: error: after previous specification in 'void Matrix::printMatrix(std::ostream&) const' [-fpermissive]

You should not specify the default argument of a function both in a declaration and in a definition:

class Matrix
{
    // ...

    // Default argument specified in the declaration...
    void printMatrix( ostream& os = cout ) const;

    // ...
};

// ...so you shouldn't (cannot) specify it also in the definition,
// even though you specify the exact same value.
void Matrix::printMatrix( ostream& os /* = cout */ ) const{
//                                    ^^^^^^^^^^^^
//                                    Remove this


    ...
}

Alternatively, you can keep the default argument specification in the definition and omit it in the declaration. What's important is that you don't have it in both.

The function has an output stream as parameter, and has the standard output ( std::cout ) as default (albeit incorrectly specified in the function definition, not in the declaration as it should be). You can do this:

// use default parameter std::cout
Matrix m + ...;
m.printMatrix();

// explicitly use std::cout
m.printMatrix(std::cout);

// write to a file
std::ofstream outfile("matrix.txt");
m.printMatrix(outfile);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM