Home > Net >  Two input types - Initializer list (C )
Two input types - Initializer list (C )

Time:02-27

I need the instance str is able to accept two diferent types. I have to use notation with {}. It should be std::initializer_list.

const UTF8String str{ };

This works:

class UTF8String {

public:
    std::string inputString;
};

int main() {    
    
    const UTF8String str{ "hello" };

    return 0;
}

This works:

class UTF8String {

public:
    int inputInt;
};

int main() {    
    const UTF8String str{ 5 };

    return 0;
}

But this doesn't work:

class UTF8String {

public:
    std::string inputString;
    int inputInt;
};

int main() {    
    
    const UTF8String str{ "hello" };
    const UTF8String str{ 5 };

    return 0;
}

CodePudding user response:

Not sure if the following meets yours needs, but it seems to work:

#include <iostream>

class UTF8String
{
   public:
      std::string inputString;
      int inputInt;
      UTF8String(const char s[]) : inputString(s) {}
      UTF8String(int i) : inputInt(i) {}
};

int main()
{
   const UTF8String str1{ "hello" };
   const UTF8String str2{ 5 };

   return 0;
}
  •  Tags:  
  • c
  • Related