是什么导致 c++ std::string 变量在传递给 class 时给出了冲突的定义

what causes c++ std::string variable gives conflicting defenition when passing to class

我有一个 class,它有一个接受字符串的构造函数; 当传入一个文字以创建一个新的瞬间时,它工作正常。 现在,当我创建一个要读入的字符串变量时,它会抛出一个错误,指出存在冲突的定义。该变量能够成功传递给非 class 函数。 这是代码:

/*********************
*
*
*draw a box around 
*words
*each word gets its 
*own line
*********************/
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <sstream>
    #include <vector>
    using namespace std;


class Box 
{
short width;// allows for an empty box to appear as two lines
short height;// makes an empty box a 2x2 box

string text;
//will only be constructed with a word
public:
Box(string& words): text(words)
{
    height = calc_height()+2;
    cout<<height -2<<endl<<text<<endl;
    width = calc_Max_length();
    cout<<width<<endl<<text;

}
private:
short calc_height()
{
    long total = text.length();
    string space = " ";
    short num_words =1; // calculated by the number of spaces, i know poor option but still hey itll mostly work assuming one word at min
    bool afterword = false;
    for(int i =0; i<text.length(); i++)
    {
        if(text[i] == ' ')
        {

            if(afterword)
            {
                num_words+=1;
                afterword=false;
            }
        }
        else
            {afterword=true;}
    //    cout<<i<<'\t'<<num_words<<endl;

    }
//    cout<<num_words;
    return num_words;

}
short calc_Max_length()
{

    short dist_between =0;
    short max = 0;
    short last = 0;
    bool afterword = false;
        for(int i =0; i<text.length(); i++)
    {
        if(text[i] == ' ')
        {
        //    dist_between = i-last;
            max = dist_between>max?dist_between:max;
            last = i;
            dist_between = 0;

        }
        else
            {
                dist_between++; 
            }
    //    cout<<i<<'\t'<<num_words<<endl;

    }
        max = dist_between>max?dist_between:max;

    return max;
}




};


void takes_string(string& s)
    {
    cout<<s;
    return;
    }


int main(void)
    {   
        string input = "crappy shit that sucks";
        takes_string(input);
    //    cin>>input;
        Box(input);

        return 0;
    }
Box(input);

...等同于...

Box input;

也就是说,它试图创建一个类型为 Box 且标识符为 input 的变量,但是已经有一个名为 inputstd::string,因此出现重定义错误。

你显然想要什么 - 一个临时的 Boxinput 字符串构造 - 应该写成 - 在 C++11 中 - 像这样...

Box{input};

FWIW,一个好的编译器应该在错误消息中非常清楚地说明这一点,例如来自 GCC coliru.stackedcrooked.com:

main.cpp: In function 'int main()':
main.cpp:99:18: error: conflicting declaration 'Box input'
         Box(input);
                  ^
main.cpp:96:16: note: previous declaration as 'std::string input'
         string input = "crappy shit that sucks";
                ^