0

I have this code but compilation failed:

class TextBlock
{
    public:
        TextBlock(std::string &s)
        {
            text = s;
        }

    private:
        std::string text;
};
int main()
{
    TextBlock tb("Hello");
    std::cout<< tb[0] << std::endl ;
}

why when the constructor is TextBlock(const std::string &s) the above code can compile success ?

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Timi
  • 892
  • 1
  • 8
  • 17
  • Temporary cannot bind to non-const (l-value) reference. – Jarod42 Sep 02 '20 at 12:56
  • sloppy speaking you need a string somewhere, a reference is just a reference. If the reference is `const` then the function is fine with taking a temporary because anyhow it wont be modified. Passing a temporary to a function that expects a non-const reference is pointless because you cannot observe the modifications, hence it makes sense that this is an error – 463035818_is_not_an_ai Sep 02 '20 at 12:57

1 Answers1

1

the constructor is specting a ref to a string do instead:

std::string  x{"hello"};
TextBlock tb(x);
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97