如何解释"operator const char *()"?在运算符重载? [英] How to interpret "operator const char*()" in operator overloading?

查看:118
本文介绍了如何解释"operator const char *()"?在运算符重载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看String类的一种实现,并注意到以下重载的==运算符.

I was looking at one of the implementation of String class and noticed the following overloaded == operator.

String f = "something";
String g = "somethingelse";
if (f == g)
    cout << "Strings are equal." << endl;

bool operator==(String sString)
{
    return strcmp(operator const char*(), (const char*)sString) == 0; 
}

除了operator const char*()以外,我了解大部分内容. 我对操作符重载有非常基本的了解,有人可以对此进行更多说明吗?

I understood most of the part except operator const char*() what exactly its been used for? I have very basic knowledge of operator overloading , can someone please throw some more light on this?

推荐答案

这是对operator const char*()成员函数的显式调用.此代码将执行相同的操作:

It is an explicit call to the operator const char*() member function. This code would do the same:

return strcmp(static_cast<const char*>(*this), (const char*)sString) == 0;

但是该代码有多个错误:

But there are more than one thing wrong with that code:

  1. 它不应该使用C-cast,而是使用C ++-cast(例如static_cast)作为正确的参数
  2. operator==应该是一个自由函数,而不是成员函数
  3. 字符串类通常不应具有operator const char*
  4. 如果String类的实现合理,则operator==应该将两个参数都用作const引用
  1. it should not use C-cast, but C++-casts (e.g. static_cast) for the right argument
  2. operator== should be a free function, not a member function
  3. A string class should normally not have an operator const char*
  4. If the String class is implemented reasonably, the operator== should take both parameters as const references

这篇关于如何解释"operator const char *()"?在运算符重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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