Domanda

Here's some code written in C++:

#include <iostream>
int main(){
    typedef map<int,int> b;
    b tC;

    b::iterator iMap;
    b().swap(tC);
}

I've tried:
b.swap(tc); but I keep getting an error.

What I can't understand is, why can't it be b.swap(tC); ?

Is this a compiler problem?

Sorry about my English.

È stato utile?

Soluzione 2

b::swap(x) (but not b.swap(x)!) would have worked if swap() was a static class method. But swap() is an instance method, and as such, can only work on instance of an object of class b (which is typedef of map<int,int>).

b().swap(x) does not emit an error because it works on instance of object of class b. However, this call is not likely to be useful, because this instance b() is immediately destroyed after instantiating.

Altri suggerimenti

Because b is a type. You can't call swap on a type. You need to build an object of type b and then call swap on it, which is what you do with b().swap(tC);

This line typedef map<int,int> b; is creating a new type called b, which has the properties of map<int,int>. Thus, in order to use type b and objects of type b you must follow the same rules as if you were using class map<int,int>.

In class map, function swap is a member function. That's why you need an object in order to use it. If it were a static function, you could call it directly on the type, although the syntax for that is a little different: b::static_function()

Because member functions can only be called via an object, you need to create an object, before calling swap on it. Therefore in:

b().swap(tC);

you are correctly creating a temporary object and swapping it with tC.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top