cpp为什么s.query被覆盖

问题描述 投票:0回答:2

我正在开发一个类,使我可以轻松构建sql语句。我提出的一个想法是使用运算符重载允许我向我的sql语句添加不同的值类型。话虽如此,问题在于,由于某种原因,每次我再次呼叫操作员时,它似乎都会覆盖前一次呼叫的影响。这是我的代码:

#include <string>
#include <iostream>
using namespace std;
class sql
{
    string query;

  public:
    sql();
    void add(int i);
    void end();
    void print();
    void add_string(string str);
    sql operator+(const string &str) const;
    sql operator+(const int &i) const;
};

sql::sql()
{
    this->query = "";
}

sql sql::operator+(const int &i) const
{
    sql result;
    result.add(i);
    return result;
}

sql sql::operator+(const string &str) const
{
    sql result;
    result.add_string(str);
    return result;
}

void sql::add_string(string str)
{
    this->query = this->query + "'" + str + "',";
}

void sql::add(int i)
{
    query = query + to_string(i) + ",";
}

void sql::end()
{
    query += ";";
}

void sql::print()
{
    cout << this->query;
}

int main()
{
    sql s;
    string s1("terry");
    int i = 10;
    s = s + s1;
    s.print();
    cout << endl;
    s = s + i;
    s.print();
}

我期望的输出是:

'terry',
'terry',10,

但相反是:

'terry',
10, 

为什么第二次使用+运算符会覆盖第一个运算符的效果?

c++ operator-overloading
2个回答
1
投票
sql sql::operator+(const int &i) const
{
    sql result;

创造一个新的,空的sql

    result.add(i);

将整数添加到空sql

    return result;
}

给定的sqlthis尚未使用。代替,

sql sql::operator+(const int &i) const
{
    sql result(*this);

copy根据当前的sql构建一个新的sql

    result.add(i);

将i添加到包含先前sql内容的sql中。

    return result;
}

你也想做同样的事情

sql sql::operator+(const string &str) const

0
投票

如果仔细观察operator +实现,很明显它不会使用左侧对象。

sql sql::operator+(const string &str) const
{
    sql result;
    result.query = this->query; // concat whatever was stored in the left-side object
    result.add_string(str);
    return result;
}
© www.soinside.com 2019 - 2024. All rights reserved.