C++;:对'的调用不匹配;(concat)(std::string&;)&x27; 我一直试图编写这个C++程序,用操作符上的操作符重载将字符串作为用户的输入连接起来(+=)。我定义了构造函数来初始化对象,并将字符串作为参数。但它仍然显示了错误

C++;:对'的调用不匹配;(concat)(std::string&;)&x27; 我一直试图编写这个C++程序,用操作符上的操作符重载将字符串作为用户的输入连接起来(+=)。我定义了构造函数来初始化对象,并将字符串作为参数。但它仍然显示了错误,c++,string,class,operator-overloading,C++,String,Class,Operator Overloading,错误:对“(concat)(std::string&)”的调用不匹配| 下面是3个文件的代码=> main.cpp #include <iostream> #include "concat.h" #include<string> using namespace std; int main() { concat ob[10]; concat result; int i; string ip; cout<<"Enter the strings upto 10 i

错误:对“(concat)(std::string&)”的调用不匹配|

下面是3个文件的代码=> main.cpp

#include <iostream>
#include "concat.h"
#include<string>
using namespace std;

int main()
{
concat ob[10];
concat result;
int i;
string ip;
cout<<"Enter the strings upto 10 in different lines.. \n";
for(i=0;i<(sizeof(ob)/sizeof(ob[0]));i++){
    cin>>ip;
    ob[i](ip);
}

while(i!=0){
    result += ob[i++];
}
cout<<result.input;
}
#include <iostream>
#include "concat.h"
#include<string>
using namespace std;

concat::concat(){
}
concat::concat(string ip)
:input(ip)
{
}
concat concat::operator+=(concat ipObj){
    this->input += ipObj.input;
    return *this;
}
#包括
#包括“海螺”
#包括
使用名称空间std;
int main()
{
concat-ob[10];
concat结果;
int i;
字符串ip;

cout这就是您的
concat
类原型的外观:

class concat
{
public:
    string input;
    concat() = default;
    concat& operator+=(const concat&);

    // assignment operator
    concat& operator=(const string& str) {  
        input = str;
        return *this;
    }
};
然后使用
ob[i]=ip;
代替
ob[i](ip)


另外,您的程序崩溃是因为您在初始化您使用的
concat
对象时编写了
result+=ob[i++];

而不是
result+=ob[--i];

。为此,您需要一个函数调用操作符(即
操作符()(字符串常量&)
在您的
concat
类型上。您可能想编写
ob[i]=concat(ip)
ob[i]=ip
(因为
std::string
中的构造函数是隐式的,所以这种方法也应该有效)。此外,在使用它之前,请始终检查输入是否成功:
如果(std::cin>>ip){…}
我确实尝试使用第二种方法进行更改,ob[I](ip)更改为ob[I]=concat(ip)以及ob[I]=ip。它执行时没有错误,但在我给出输入后,程序崩溃了。它甚至在那之后也崩溃了。对不起,我从
I--
更改为
--I
。这是因为
I==sizeof(ob)/sizeof(ob 0])
此时,它是
最大索引+1
导致超出范围异常。因为
i--
首先获取
i
的值,然后才递减,我将while循环更改为for循环,并使用i++按输入的顺序递增。并将ob[i](ip)替换为ob[i]=(ip)它解决了问题。但我仍然不认为
class
=
string
是最佳实践
class concat
{
public:
    string input;
    concat() = default;
    concat& operator+=(const concat&);

    // assignment operator
    concat& operator=(const string& str) {  
        input = str;
        return *this;
    }
};