c++ - 对‘(std::string {aka std::basic_string<char>}) (int, char)’的调用没有匹配
阿神
阿神 2017-04-17 11:13:17
0
2
866

之前在 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 = "      "; // 六个空格
阿神
阿神

闭关修行中......

reply all(2)
Ty80
#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.

巴扎黑

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template