问题描述
我想向字符串类添加一个新的成员函数"charReplace".该功能将用一个字符替换所有出现的一个字符.所以我准备了一个示例代码.
I want to add a new member function "charReplace" to the string class. The function will replace all the occurances of one character with another character. So I prepared a sample code.
#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;
}
但是它不起作用.编译时在第4行出现以下错误.
But it is not working. I am getting the following error in line 4 while compiling.
我知道通过创建非成员函数很容易获得相同的结果.但是我想使用成员函数来做到这一点.那么,有没有办法在c ++中做到这一点?
I know that it is quite easy to get the same result by creating a non-member function. But I want to do it using a member function. So, is there a way to do this in c++?
P.S.我还是C ++新手.我已经使用几个月了.因此,请尝试使您的答案易于理解.
P.S. I am still new with c++. I have been using it for a few months only. So, please try to make your answer easy to understand.
推荐答案
您不能.这是C ++,而不是JavaScript(您可以在其中编写任何类的原型).
you can't. this is C++, not JavaScript (where you can prototype any classes).
您的选择是:
- 继承力
- 组成
- 独立功能
这篇关于如何在C ++的内置类中添加成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!