My Opera is closing 3rd of March

古日

今天发现了c++符号重载的一个非常实用的使用实例。

在看LiteSQL这个项目的源码的时候发现一段非常有趣的代码:

string ind = string(" ") * indent;


我的第一反应是:string 竟然还可以这样用?随即写了一段测试代码:

#include <iostream>
#include <string>

using namespace std;


int main(int argc, char *argv[])
{
    string str = string("#") * 30;

    cout << str << endl;

    return 0;
}


编译后却得到这样的错误:

$ g++ -o tt tt.cc
tt.cc: In function ‘int main(int, char**)’:
tt.cc:9: error: no match for ‘operator*’ in ‘std::basic_string<char, std::char_traits<char>, std::allocator<char> >(((const char*)"#"), ((const std::allocator<char>&)((const std::allocator<char>*)(& std::allocator<char>())))) * 30’



由此看来这并不是STL的标准特性,于是想起了C++的符号重载,马上使用 grep:

$ grep "operator\*" * -R

...

src/library/string.cpp:std::string operator*(int amount, const std::string &s) {
src/library/string.cpp:std::string operator*(const std::string &s, int amount) {


这下都明白了:

std::string operator*(int amount, const std::string &s) {
    std::string res;
    for(;amount>0;amount--)
        res += s;
    return res;
}
	
std::string operator*(const std::string &s, int amount) {
    return amount * s;
}

Write a comment

New comments have been disabled for this post.

February 2014
M T W T F S S
January 2014March 2014
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28