Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The correct way to define default argument for a friend function in C++

Tags:

c++

c++11

xcode5

I want to specify a default value for a friend function, as follows:

friend Matrix rot90 (const Matrix& a, int k = 1);

When compiling this line with Xcode 5.1.1, I get the following error

./Matrix.hh:156:19: error: friend declaration specifying a default argument must be a definition

What is the proper way of fixing it?

Thanks!

like image 952
Anastasia Avatar asked Apr 28 '14 06:04

Anastasia


People also ask

Which is the correct condition for the default arguments?

Which is the correct condition for the default arguments? Explanation: The default arguments must be declared at last in the argument list. This is to ensure that the arguments doesn't create ambiguity.

What is a default argument in C?

A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.

What is a default argument how do you define one?

In computer programming, a default argument is an argument to a function that a programmer is not required to specify. In most programming languages, functions may take one or more arguments. Usually, each argument must be specified in full (this is the case in the C programming language).

How can we use default arguments in the function?

If a function with default arguments is called without passing arguments, then the default parameters are used. However, if arguments are passed while calling the function, the default arguments are ignored.


1 Answers

The standard says (§8.3.6):

If a friend declaration specifies a default argument expression, that declaration shall be a definition and shall be the only declaration of the function or function template in the translation unit.

That is, if you specify the default argument on the friend declaration, you must also define the function right then and there. If you don't want to do that, remove the default argument there and add a separate declaration for the function that specifies the default arguments.

// forward declarations:
class Matrix;
Matrix rot90 (const Matrix& a, int k = 1);

class Matrix {
    friend Matrix rot90 (const Matrix&, int); //no default values here
};
like image 50
ComicSansMS Avatar answered Sep 28 '22 07:09

ComicSansMS