[英]Can't find the problem in the string fuction
所以問題是這樣的
error: invalid operands of types ‘const char [20]’ and ‘float’ to binary ‘operator<<’
這是我的字符串函數得出的。 我嘗試在谷歌中搜索,但沒有任何結果。
#include <iostream>
#include <string>
using namespace std;
class Rectangle
{
public:
Rectangle () : length(1.0), width(1.0)
{
}
Rectangle(float l, float w) :length(l), width(w)
{
}
void setLength(float l)
{
length = l;
}
float getLength()
{
return length;
}
void setWidth(float w)
{
width = w;
}
float getWidth()
{
return width;
}
double getArea()
{
return width * length;
}
double getPerimeter()
{
return 2 * (width + length);
}
string toString()
{
string s1 = "Rectangle [Length ="<<getLength()<<", width = "<<getWidth()<<"]";
return s1;
}
private:
float length = 1.0;
float width = 1.0;
};
這是我的代碼。 那么我的字符串函數有什么問題呢? PS。 另外,如果您指出我錯過的其他問題,那就太好了。
您可能正在通過<<
與連接字符串混合打印到 output stream。
要連接 2 個std::string
,請改用+
運算符。 該運算符還可以處理類似於char const*
之類的字符串,但前提是其中一個操作數已經是std::string
。
使用std::to_string
將數字轉換為字符串表示:
std::string toString()
{
std::string s1 = "Rectangle [Length =" + std::to_string(getLength()) + ", width = " + std::to_string(getWidth()) + "]";
return s1;
}
或者,使用std::ostringstream
創建允許您使用<<
運算符的字符串:
#include <sstream>
#include <utility>
...
std::string toString()
{
std::ostringstream stream;
stream << "Rectangle [Length =" << getLength() << ", width = " << getWidth() << "]";
return std::move(stream).str();
// note: str on a rvalue reference may be cheaper starting C++20
// in prior versions the line above equivalent to
// return stream.str();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.