Files
OOP-Cpp/oop_hw4/hw7/aws.txt
2025-08-11 00:01:30 +08:00

12 lines
898 B
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

一、为什么重载 + 一般用自由函数形式?
原因:+ 具有交换律,左操作数不一定是你定义的类对象。自由函数可以让任意顺序都合法,因为左右参数都可以指定类型。
二、为什么重载 += 一般用成员函数形式?
原因a += b 本质是修改 a左操作数必须能访问并修改其内部状态。自由函数虽然也能写但不能直接访问私有成员需要提供 setter 或 friend不优雅。
三、为什么重载 = 必须是成员函数?
原因a = b 是赋值,修改的是左操作数的内部状态,必须有 this 指针。C++ 强制 operator= 只能是成员函数(标准规定)。
四、为什么重载 << 要用自由函数?
原因std::cout << obj 左操作数是 std::ostream你没法修改它的定义。如果不用自由函数就会变成 trip << cout不符合逻辑