我可以禁止在对象实例上调用静态方法吗? [英] Can I forbid calling static methods on object instance?
本文介绍了我可以禁止在对象实例上调用静态方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的课堂上有很多转换功能:
I have class with lots of conversion functions:
class Something {
public:
string toXml();
string toJson();
...
static Something fromXml(string); // factory
static Something fromJson(string); // factory
...
};
因为可以在实例上调用静态函数, 编写这样的代码很容易:
Because static functions can be called on instance, it is easy to write code like this:
Something sss;
... initializing sss ...
string xml1 = sss.toXml();
sss.fromXml(xml1); // does nothing
string xml2 = sss.toXml();
assert(xml1 == xml2); // always true
所以我想禁止从XXX上调用对象,或者 至少让他们做一些不同的事情.
So I want to forbid calling fromXXX on objects, or at least make them do something different.
有没有办法做到这一点?
Is there a way to do this?
推荐答案
他们真的需要成为班级成员吗?防止这种情况的明显方法是使它们具有自由功能.
Do they really need to be class members? The obvious way to prevent this is to make them free functions.
这篇关于我可以禁止在对象实例上调用静态方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文