Domanda

I have the following problem. I have a class with a private inner class. I now would like to implement a friend swap function for the inner class. However I do not know how to make a non inline swap function. If I define it in the inner class it all works fine. If someone can show me how to make it non inline I would greatly appreciate it :)

Some code do illustrate the problem:

class Outer
{
    class Inner
    {
        int data;

        friend swap(Inner& lhs, Inner& rhs)  // what is the syntax to 
        {                                    // make this function non inline?
            using std::swap;
            swap(lhs.data, rhs.data);
        }       
    }
}
È stato utile?

Soluzione

I think I found the solution. Seemed a bit strange to me at first, but it makes sense. When I tried to write the definition of the swap function in the .cpp file the compiler told me that swap does not have access to Inner since it is private. The solution was to make it this swap function a friend of Outer as well!

In code:

.h:

class Outer
{
    class Inner
    {
        int data;

        friend swap(Inner& lhs, Inner& rhs);     
    }
    friend swap(Inner& lhs, Inner& rhs);
}

.cpp:

void swap(Outer::Inner& lhs, Outer::Inner& rhs)
{
    using std::swap;
    swap(lhs.data, rhs.data);
} 

Altri suggerimenti

To do it you need to define it in a .cpp file just like any other function:

Outer::Inner::swap(Outer::Inner& lhs, Outer::Inner& rhs)
{
    using std::swap;
    swap(lhs.data, rhs.data);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top