如何使用此唯一运算符重载函数

时间:2015-05-10 00:45:47

标签: c++ operator-overloading

我在使用sqlapi期间遇到了这个操作员过载,这完全符合我的需要,但我不确定它是如何工作的。

sqlapi.h

class SQLAPI_API SAString
{
public:
//stuff

//! Return pointer to const string
operator const SAChar *() const;

//stuff
}

我知道如何使用它的唯一方法是因为intellisense看起来不漂亮:

char* chPointer = SAStringObj.operator const SAChar*();

问题:

有没有更好看的方法来调用这个重载的运算符?

有人可以剖析这个函数标题告诉我们的函数吗?

" * operator const SAChar ()const; "

1 个答案:

答案 0 :(得分:3)

这是一个隐式转换运算符,用于将SAString转换为const SAChar *。只要在期望SAString的上下文中使用const SAChar *,就会隐式调用它(除非它是不明确的)。

void foo(const SAChar *);

SAString myString("bar");

foo(myString);
const SAChar *myCharPtr = myString;

您可以使用static_cast强制它在其他环境中使用:

static_cast<const SAChar *>(myString)

您可以boost::implicit_cast使用boost::implicit_cast<const SAChar *>(myString)

explicit operator const SAChar *() const;

在C ++ 11中,您可以拥有显式强制转换运算符,该运算符仅在显式强制转换上下文中有效:

const

最后的c:\Python34\Scripts\mysite>python manage.py makemigrations polls Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "c:\Python34\lib\site-packages\django\core\management\__init__.py", line 338, in execute_from_command_line utility.execute() File "c:\Python34\lib\site-packages\django\core\management\__init__.py", line 312, in execute django.setup() File "c:\Python34\lib\site-packages\django\__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "c:\Python34\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "c:\Python34\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "c:\Python34\lib\importlib\__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked File "<frozen importlib._bootstrap>", line 1129, in _exec File "<frozen importlib._bootstrap>", line 1471, in exec_module File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed File "c:\Python34\Scripts\mysite\polls\models.py", line 3, in <module> class Question(models.Model): File "c:\Python34\Scripts\mysite\polls\models.py", line 7, in Question class Choice(models.Model): File "c:\Python34\Scripts\mysite\polls\models.py", line 8, in Choice question = models.ForeignKey(Question) NameError: name 'Question' is not defined 具有通常的含义,就像普通的成员函数一样。