gpt4 book ai didi

c++ - 为什么必须在运算符重载中提供关键字 const

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:12:13 24 4
gpt4 key购买 nike

只是好奇为什么参数在操作重载中必须是常量

CVector& CVector::operator= (const CVector& param)
{
x=param.x;
y=param.y;
return *this;
}

难道你不能轻松地完成这样的事情吗??

CVector& CVector::operator= (CVector& param) //no const
{
x=param.x;
y=param.y;
return *this;
}

不是当某些东西变成常量时,它在应用程序的剩余生命周期中是不可更改的吗??这在操作重载方面有何不同???

最佳答案

你不需要常量:

@numerical25: Just curious on why a param has to be a const in operation overloading

这不是必需的,但这是一个很好的设计决策。

请参阅 C++ 标准第 12.8-9 节:

A user-declared copy assignment operator X::operator= is a non-static non-template member function of class X with exactly one parameter of type X, X&, const X&, volatile X& or const volatile X&


不过我认为这是个好主意:

使用 const 参数对我来说似乎是一个合乎逻辑的设计决定,因为你想确保其他值不会被改变。

它告诉其他使用你的类的人你不会改变 other 值当你说这样的话时:myObject = other; 并且它强制执行这一点所以你不能意外地改变 other

此外,如果您允许对对象的非 const 引用作为参数,那么您就是在限制可以使用您的函数的对象的数量。如果它是 const,它可以用于 const 和非 const 的参数。如果您的参数是非 const,则它只能由非 const 的参数使用。


const 仅适用于当前引用,不适用于对象:

@numerical25: Isn't when something becomes a const, it is unchangeable for the remainder of the applications life ?? How does this differ in operation overloading ???

常量引用就是一个常量引用。它不会改变您传入的实际对象的常量性。


非常量运算符重载的示例:

下面是一个运算符重载的例子,其中参数不是const。
不过我不建议这样做:

class B
{
public:
const B& operator=(B& other)
{
other.x = 3;
x = other.x;
return *this;
}

int x;
};


void main(int argc, char** argv[])
{
B a;
a.x = 33;
B b;
b.x = 44;
a = b;//both a and b will be changed
return 0;
}

关于c++ - 为什么必须在运算符重载中提供关键字 const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2949976/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com