如何在c ++中的内置类中添加成员函数?

Tan*_*Das 2 c++ string member-functions

我想在字符串类中添加一个新的成员函数"charReplace".该函数将用一个字符替换一个字符的所有出现.所以我准备了一个示例代码.

#include <iostream>
#include <string>

std::string string::charReplace(char c1, char c2) { //error in this line
    while(this->find(c1) != std::string::npos) {
        int c1pos = this->find(c1); //find the position of c1
        this->replace(c1pos, 1, c2); //replace c1 with c2
    }
    return *this;
}

int main() {
    std::string s = "sample string";

    s.charReplace('s', 'm') /* replace all s with m */

    std::cout << s << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

但它没有用.我在编译时在第4行中收到以下错误.

错误:'string'没有命名类型

我知道通过创建非成员函数可以很容易地得到相同的结果.但我想用成员函数来做.那么,有没有办法在c ++中做到这一点?

PS我仍然是c ++的新手.我一直在使用它几个月.所以,请尽量让您的答案易于理解.

Dav*_*aim 8

你不能.这是C++,而不是JavaScript(您可以在其中构建任何类的原型).

你的选择是:

  1. 遗产
  2. 组成
  3. 独立功能


Gal*_*lik 5

您无法添加到std::string界面,但可以执行以下操作:

#include <string>
#include <iostream>
#include <algorithm>

int main()
{ 
    std::string s = "sample string";

    std::replace(s.begin(), s.end(), 's', 'm'); /* replace all s with m */

    std::cout << s << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

输出:

mample mtring
Run Code Online (Sandbox Code Playgroud)