【问题标题】:Replicating Python functions in C++ [duplicate]在 C++ 中复制 Python 函数 [重复]
【发布时间】:2014-05-29 20:44:18
【问题描述】:

我最近从 C 切换到 OOP 语言 - C++Python 3.4

我注意到Python 有很多东西是C++ 无法比拟的 其中之一是易于调用函数。

所以我决定以某种方式实现在 C++ 中使用 STL 进行函数调用的 python 方式。

我从“字符串”类开始。

在 Python 中,我可以这样做:

str="hello world   "
str.strip().split()

首先,去掉字符串末尾的尾随空格,然后在空格处将字符串分成两半

现在是 整洁 我希望能够以这种方式调用函数,即object.func1().func2().func3() 等等

因为我对 stl 类“字符串”一无所知,所以我从自己制作的类“MYstring”开始

class MYstring
{
    string str;
public:
    //constructor
    MYstring(string str)
    {   setter(str);    }

    //setter function
    MYstring& setter( string str )
    {   this->str=str;
        return *this;
    }

    //getter_str function
    string getter_str()
    {   return str;
    }

    unsigned int getter_size()
    {   return str.size();
    }

    //modifier function(s)
    MYstring& split(char x='\0')
    {   string temp="";
        for(int i=0; i<str.size(); i++)
        {   if(this->str[i-1] == x)
                break;
            temp += str[i];
        }
        this->str=temp;
        return *this;
    }

    MYstring& strip()
    {
        for(int i=this->str.size() - 1; i>=0; i--)
        {   if(this->str[i] == ' ')
                this->str.erase(i);
            else if(isalnum(this->str[i]))
                break;
        }
        return *this;
    }
};

为了测试类及其成员函数,我使用了以下main()

int main()
{   //take a user-defined string-type input
    string input;
    cout<<"Enter a string: ";
    getline(cin,input);

    // create an object of class 'MYstring'
    // and initialise it with the input given by the user
    MYstring obj(input);

    //take the character at which the string must be split
    cout<<"\nEnter character to split the string at: ";
    char x;
    cin>>x;

    //display original input
    cout<<"\n\nThe user entered: "<<obj.getter_str();
    cout<<"\nSize = "<<obj.getter_size();

    obj.strip().split(x);//  <--- python style function call
    cout<<"\n\nAfter STRIP and SPLIT: "<<obj.getter_str();
    cout<<"\nSize = "<<obj.getter_size();

    return 0;
}

而且有效

所以,最后这是我的问题:

如何为C++ STL string class 创建和使用相同的splitstrip 函数? 是否可以在 STL 中使用我们自己创建的方法?

欢迎提出任何建议。

【问题讨论】:

    标签: c++ function python-3.x


    【解决方案1】:

    您可以扩展类 std::string 并使用扩展类。因此,您的类将具有 STL 字符串的所有功能以及其他方法。

    class mystring: public std::string {
       ...
    };
    

    【讨论】:

    • @JBL 只是不要使用虚函数...如果你这样做编译器会警告你。
    • 如果你不添加额外的属性你怎么会有切片?
    • @JBL 但是谁用new 创建strings 呢?这没什么大不了的。但我认为它没有任何优于编写函数以在string 上运行的优势。
    【解决方案2】:

    根据经验和在 cmets 中星标帖子的链接中涵盖的主题,我不会将 STL 类子类化,而是像您一样创建您自己的类。

    而且,除了你的 std::string 复制构造函数之外,你还可以添加一个 typecast-to-std::string 运算符重载,所以在工作时可以很容易地在你的对象和 std::string 之间进行代码转换使用带有 std::string 的库。

    【讨论】:

    • 那么,什么是一个足够好的解决方法来防止发生你刚才指出的事情?
    猜你喜欢
    • 2015-07-15
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 2021-05-11
    • 2015-08-09
    • 2020-11-14
    相关资源
    最近更新 更多