是否可以在C ++中将成员函数添加到数据类型? [英] Is it possible add member function to data type in C++?

查看:66
本文介绍了是否可以在C ++中将成员函数添加到数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用"String.prototype"为javascript中的数据类型创建函数.在C ++中也可以吗?

I want to create a function to data types like in javascript with "String.prototype". Is it possible in C++ too?

例如:

int functionName()
{
    if(this.string == "something") {
        return 1;
    }

    return 0;
}

std::string mystring = "text";

int result = mystring.functionName();

推荐答案

不,不是.

您可以从类继承并将新成员添加到新的派生类,但也可以考虑使用组成,因为继承并不总是合适的.有关这方面的更多信息,请查阅您的书中有关面向对象编程的章节.

You can inherit from a class and add new members to the new derived class, but also consider composition because inheritance isn't always appropriate. Consult the chapter in your book about object oriented programming for more information on that.

如果不需要访问私有数据,还可以考虑使用免费(非成员)功能.同样,请小心使用吸气剂/装填剂过量使用它

Also consider free (non-member) functions if you don't need any access to private data. Similarly, be careful of overdoing it with the getters/setters!

这篇关于是否可以在C ++中将成员函数添加到数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆