如何使用+运算符连接字符串

时间:2019-10-13 02:43:32

标签: c++ string concatenation

为什么一个被允许而另一个产生错误。任何可以解释的人。

#include<string>
using namespace std;
int main()
{
    string s3 = "Why";
    string s11 = "hello" + " , " + s3;  // It gives error
    string s11 =  s3 + " , " +"hello" ; // This works fine.
}

2 个答案:

答案 0 :(得分:3)

由于运算符的优先级,是行

string s11 = "hello" + " , " + s3;

处理为

string s11 = ("hello" + " , " ) + s3;

子表达式"hello" + " , "不合法。 第一项是char const [6]类型(由6个char const组成的数组),第二项是char const [4]类型(由4个char const组成的数组)。

两者之间没有+运算符。这就是为什么它是编译器错误。


第二行

string s11 =  s3 + " , " + "hello" 

处理为

string s11 =  (s3 + " , ") + "hello" 

子表达式s3 + " , "有效,因为支持该操作的operator+有重载。子表达式的计算结果为std::string。因此,后续的+ "hello"也是受支持的操作。

答案 1 :(得分:1)

var WipData = { labels : ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "Butter1", "n", "o", "p", "r", "s", "t"], datasets: [ { label : 'Data1', fillColor : ['#444340','#444340','#444340','#444340','#444340','#444340','#3c1c09','#3c1c09','#3c1c09','#3c1c09','#3c1c09','#3c1c09','#3c1c09','#f39c12','#f39c12','#f39c12','#f39c12','#664b3a','#a66c47','#a66c47'], strokeColor : ['#444340','#444340','#444340','#444340','#444340','#444340','#3c1c09','#3c1c09','#3c1c09','#3c1c09','#3c1c09','#3c1c09','#3c1c09','#f39c12','#f39c12','#f39c12','#f39c12','#664b3a','#a66c47','#a66c47'], pointColor : ['#444340','#444340','#444340','#444340','#444340','#444340','#3c1c09','#3c1c09','#3c1c09','#3c1c09','#3c1c09','#3c1c09','#3c1c09','#f39c12','#f39c12','#f39c12','#f39c12','#664b3a','#a66c47','#a66c47'], pointStrokeColor : '#c1c7d1', pointHighlightFill : '#fff', pointHighlightStroke: 'rgba(220,220,220,1)', data : datatochart } ] } var barChartCanvas = $('#chart-wip-bar').get(0).getContext('2d') var barChart = new Chart(barChartCanvas) var barChartOptions = { scaleBeginAtZero : true, scaleShowGridLines : true, scaleGridLineColor : 'rgba(0,0,0,.05)', scaleGridLineWidth : 1, scaleShowHorizontalLines: true, scaleShowVerticalLines : true, barShowStroke : true, barStrokeWidth : 2, barValueSpacing : 5, barDatasetSpacing : 1, legendTemplate : '<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span style="background-color:<%=datasets[i].fillColor%>"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>', responsive : true, maintainAspectRatio : true, multiTooltipTemplate: "<%= datasetLabel %>: <%= value %><%if (datasetLabel=='Achievement'){%> %<%}%>", } barChartOptions.datasetFill = false barChart.Bar(WipData, barChartOptions); 是字符串文字,其类型为字符数组("hello")。 char[6]仅为operator+定义。您可以使用udl std::string使其s

std::string