简体   繁体   中英

how can I solve this strange c++ std map problem?

I have written some test code like this:

#include <iostream>
#include <map>
#include <string>

using namespace std;

using TEST_OBJ = std::map<std::string, std::string>;

class ABB
{
public:
    ABB(const TEST_OBJ & src) : m_src(src) {}
public:
    void func() { std::cout << "hello"; }
private:
    TEST_OBJ m_src;
};

int main()
{
    TEST_OBJ o;

    ABB a(TEST_OBJ(Afdafdsaa));


    return 0;
}
  1. the compiler g++ successfully compiles this code with undefined variable “Afdafdsaa”
  2. g++ typeid(a).name told me the variable "a" is a function

Can anybody help me?

Not entirely sure what you're asking. The problem is insoluble in the sense of making the code work, since Afdafdsaa is undefined.

However, if you want to get more reasonable errors, then the best practice is to use the C++ initializer syntax. The basic problem seems to be that the declaration of a is being read as a function declaration, not an object declaration. This is because round brackets are used in both cases.

With the initializer syntax, curly braces are used to make it clear that we are dealing with initialization.

Thus, change the line in question to:

ABB a{ TEST_OBJ{Afdafdsaa} };

and you'll get a clear error.

The idea is to get into the habit of using curly braces all the time for initialization. If everything's fine they work just like round brackets, but when things go wrong it means the compiler can understand better what you wanted to do.

Looking at this code, it creates a new variable:

#include <map>
using std::map;
int main()
{
    map<string, string>(adsfafasdf);
    map<string, string>::iterator it = adsfafasdf.begin();
    return 0;
}

Same thing happens when instantiating template/nontemplate class or type

template<class T> class cls
{
public: void v(){cout<< "v"<< endl;}
};
int main()
{
    int(i);
    i = 123;
    cls<string>(bazz);
    bazz.v();
    return 0;
}

In the case of your TEST_OBJ(Afdafdsaa) the Afdafdsaa is defined right in place, but not visible outside the scope of (), and is not returned to constructor of a. That's why a is treated as a declaration of function that returns ABB and not an instantiation of an object of type ABB.

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