Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

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

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...