c++ - 指针运算符可以在 C++ 中重载吗?

标签 c++

运算符 = 是否可以为类指针重载。此示例尝试为指针“Cutie*”重载“operator =”:

class Cutie    
{
public:
    int Krait;

    Cutie() : Krait(0)
    {
    }
};

Cutie* operator = (Cutie* p, Cutie* q)
{
    if(p == 0)
    {
        if(0 < Krait)
            Krait--;
    }
    else
        Krait++;
}

以上定义有误。我正在寻找一个计算指针赋值的定义:

Cutie c;
Cutie* p = 0;
p = &c;

现在 'p -> Krait' 应该是 '1'。

最佳答案

不,你不能有一个只接受指针作为参数的非成员重载运算符函数:

An operator function shall either be a non-static member function or be a non-member function and have at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration.

关于c++ - 指针运算符可以在 C++ 中重载吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15416840/

相关文章:

c++ - 如何沿所有轴正确旋转四元数?

c++ - Xerces-C 上的 DOM 元素内存分配管理

c++ - boost::regex_constants::error_type 到字符串

python - 使用 ctypes : undefined symbol 将 C++ 函数导出到 python

c++ - 为什么 "defau4t"在 switch 语句中是合法的?

c++ - boost::bind 打破了严格的别名规则?

c++ - gcc是否将非常量表达式函数的内置函数视为常量表达式

c++ - 货币选择有效,除非用户选择欧元或 'e'

c++ - 在 C++ 中通过引用选项传递

c++ - C++11、14 或 17 是否提供了一种从 decltype() 中获取参数的方法?