Reputation: 22
I have a class that has one constructor that takes a string; when a literal was passed in to create a new instant it worked fine. Now when I create a string variable to have read in it throws an error saying there are conflicting definitions. The variable is able to be passed to a non-class function successfully. Here is the code:
/*********************
*
*
*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;
}
Upvotes: 1
Views: 1721
Reputation: 106068
Box(input);
...is equivalent to...
Box input;
That is, it's trying to create a variable of type Box
with identifier input
, but there's already a std::string
called input
, hence the redefinition error.
What you obviously want - a temporary Box
constructed from the input
string - should be written - in C++11 - like this...
Box{input};
FWIW, a good compiler should make this pretty clear in the error message, e.g. from GCC on 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";
^
Upvotes: 3