search

Home  >  Q&A  >  body text

c++ - 对‘(std::string {aka std::basic_string<char>}) (int, char)’的调用没有匹配

之前在 main 函数里,赋值 6 个空格给一个变量可以执行

int main()
{
   string sidebar(6, ' ');  
   return 0;
}

之后在类里面

class somethig
{
public:
    void do_something()
   {
       sidebar(6, ' ');
       // 或者是
       sidebar =  sidebar(6, ' ');
       // 都出错
   }
private:
    string sidebar;
};

g++ 编译后就会出错

对‘(std::string {aka std::basic_string}) (int, char)’的调用没有匹配

有没有像 sidebar(6, ' ') 这样简洁实现跟下面一样效果的代码?

sidebar = "      "; // 六个空格
阿神阿神2883 days ago896

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 11:15:17

    #include <string>
    
    class something
    {
    public:
        // -- 1
        something(): sidebar(6, ' ') {}
        void do_something()
        {
            // -- 2
            sidebar = string(6, ' ');
        }
    private:
        string sidebar;
    };
    

    Or as shown in 1, initialize member variables in the constructor. This feature is called "constructor initialization list".
    Or assign it a value in a member function, as shown in 2.

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 11:15:17

    The poster needs to understand the difference between C++ object copying and assignment, as well as the detailed differences in syntax

    reply
    0
  • Cancelreply