【解決方法】C++文字列コンストラクタ – boolがcharとして扱われるのはなぜですか?


やあ! すでにここで説明されている可能性がありますが、見つかりませんでした:-(
たとえば、2 つの演算子を使用してクラスを定義したとします (他の f-nalty に加えて):

class MyClass
{
      public:
           operator bool() const;
           operator const std::string() const;
}

さて、このクラスを次のように使用するとします。

MyClass mc;
if(mc) // the bool operator invoked
{
      std::string myString{ mc };
}

もし私が 予想 コピー演算子を使用して構築された文字列と const std::string MyClass の演算子ですが、これは正しくありません 🙁

それ以外の

operator bool() const;

used および using を使用して構築された文字列

basic_string( std::initializer_list<CharT> ilist,
              const Allocator& alloc = Allocator() );

私が書いても同じことが起こります:

std::string a{true, true, true, false, true, 'a'};
or std::string b{true};

これはイニシャライザ リストですが、次の制限はありません。 char型要素? char 値に変換できる任意の値がここで許可されるということですか?

私が試したこと:

私はそれを使って遊んだ コンパイラ エクスプローラ それは正しいようです!?

解決策 2

変化する

MyClass mc;
if(mc) // the bool operator invoked
{
      std::string myString{ mc };
}

に:

MyClass mc;
	if (mc) // the bool operator invoked
	{
		std::string myString(mc);
	}

あなたに電話します

MyClass::operator const std::string();

ご覧のとおり、{} は () と異なる場合があります

解決策 1

And the code for operator bool() const; and also operator const std::string() const; loos like?

このようにsmth:

class test
{
    std::string data;

    public:

    test(const std::string& d) : data{d}
    {}

    operator bool() const 
    {
        return !data.empty();
    }

    operator const std::string&() const
    {
        return data;
    }

};

————————-

You have not explained exactly what happens when you run this code.
.....
test t{"hello"};

....

if 
{
  std::string s{t};
  sdt::cout << s << "\n";
}

コンソールで実行すると、「顔」(0x01のASCII)が出力されました

コメント

タイトルとURLをコピーしました