【发布时间】:2015-05-05 01:38:01
【问题描述】:
我有一个类,它有一个带字符串的构造函数; 当传入一个文字以创建一个新的瞬间时,它工作正常。 现在,当我创建一个要读取的字符串变量时,它会抛出一个错误,指出存在冲突的定义。该变量能够成功传递给非类函数。 代码如下:
/*********************
*
*
*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;
}
【问题讨论】:
-
真的吗?文字不应该起作用。参数应该是
const string &。 -
EJP 是对的。非
const参数无法绑定到临时对象,因此无法将字符串文字传递给您的参数。如果你想接受字符串文字作为输入,你必须接受输入作为const引用。 -
您的实际错误信息是什么?
-
“冲突定义”并不表示参数类型不正确。它表明您对某事有多种定义。
-
@EJP 在我将构造函数参数更改为引用之前,它已使用文字。
标签: c++ string class constructor