【发布时间】:2013-03-11 19:12:05
【问题描述】:
是否可以只为一个函数重载一个运算符。我想覆盖 '->' 运算符,但仅在使用 print 函数( ->print() )调用它时。我知道这是一个奇怪的请求,但我正在努力实现某个 API,我需要这样的东西。
例如:
Cat cat;
cat.walk();
cat->print(); //I want to overload only this call
但是,我不想在所有情况下都重载“->”运算符。例如:
Cat* cat;
cat->walk(); //this should work normally
cat->print(); //this wouldn't call the print() function,
//since I overloaded cat->print()
【问题讨论】:
-
Cat* cat; cat->print();那么这到底应该做什么呢?不应该编译还是什么? -
注意当
->的左边是指针时,箭头操作符总是有它的内置含义,没有operator->会改变表达式的含义。
标签: c++ operator-overloading overloading