const MyInt operator - () const { return MyInt(-n); }和const MyInt operator - (MyInt& myInt) { return MyInt(-myInt.n); }
时间: 2024-04-07 07:27:58 浏览: 18
这两个函数都是重载运算符 "-",分别实现取反和负数运算。
第一个函数 const MyInt operator - () const 是重载一元负号运算符(即取反运算符),它返回一个 MyInt 类型的 const 对象。在函数体中,使用了一个匿名对象 MyInt(-n),并将其返回。这个匿名对象的值是原对象的相反数。
第二个函数 const MyInt operator - (MyInt& myInt) 是重载二元负号运算符(即负数运算符),它接受一个 MyInt 类型的引用作为参数,返回一个 MyInt 类型的 const 对象。在函数体中,使用了一个匿名对象 MyInt(-myInt.n),并将其返回。这个匿名对象的值是参数对象的相反数。
需要注意的是,第二个函数中的参数是一个非 const 引用,这意味着它可以修改原对象,而第一个函数中的对象是 const 的,不能被修改。因此,第一个函数适用于常量对象,第二个函数适用于非常量对象。
相关问题
#include <iostream> using namespace std; class MyInt { private: int n; public: MyInt() {} MyInt(int n) :n(n) {} MyInt& operator ++()//前置++ { n++; return *this; } const MyInt operator ++(int)//后置++ { MyInt temp(*this); n++; return temp; } void display() { cout << n << endl; } }; int main() { MyInt t1(5), t2, t3; t2 = ++t1; t1.display(); t2.display(); t3 = t2++; t2.display(); t3.display(); return 0; }逐句解析
这段代码是一个简单的 C++ 程序,主要演示了前置和后置自增运算符的重载。
首先,包含了头文件 iostream,用于输入输出。使用了命名空间 std。
接下来,定义了一个名为 MyInt 的类,其中包含了一个私有成员变量 n 和三个公有成员函数:一个默认构造函数、一个带参数的构造函数、以及一个重载了前置和后置自增运算符的函数。
重载前置自增运算符的函数返回了一个 MyInt 类型的引用,将 n 的值加一,并返回自身对象的引用。
重载后置自增运算符的函数返回了一个 const MyInt 类型的对象,首先将自身对象拷贝一份到一个临时对象 temp 中,然后将 n 的值加一,并返回这个临时对象 temp。
最后,定义了主函数 main,其中定义了三个 MyInt 类型的对象 t1、t2 和 t3。首先用 t1 初始化 t2,将 t1 的值加一并赋值给 t2。然后用 t2 初始化 t3,将 t2 的值加一并赋值给 t3。最后输出 t1、t2 和 t3 的值。
运行结果为:
6
6
7
6
解释:
首先,t1 的初始值为 5,调用前置自增运算符后 t1 的值变为 6,然后将 t1 赋值给 t2,所以 t2 的值也为 6,输出 t1 和 t2 的值均为 6。
然后,将 t2 赋值给 t3,调用后置自增运算符后 t2 的值变为 7,但 t3 的值还是之前的 6,输出 t2 和 t3 的值分别为 7 和 6。
.以int变量为对象,设计一个类,给出所有成员函数的声明
以下是以int变量为对象的类的成员函数声明:
```cpp
class MyInt {
public:
MyInt(); // 默认构造函数
MyInt(int value); // 带参构造函数
MyInt(const MyInt& other); // 拷贝构造函数
~MyInt(); // 析构函数
int getValue() const; // 获取对象的值
void setValue(int value); // 设置对象的值
MyInt& operator=(const MyInt& other); // 赋值运算符重载
MyInt operator+(const MyInt& other) const; // 加法运算符重载
MyInt operator-(const MyInt& other) const; // 减法运算符重载
MyInt operator*(const MyInt& other) const; // 乘法运算符重载
MyInt operator/(const MyInt& other) const; // 除法运算符重载
MyInt operator%(const MyInt& other) const; // 取模运算符重载
bool operator==(const MyInt& other) const; // 相等运算符重载
bool operator!=(const MyInt& other) const; // 不等运算符重载
bool operator<(const MyInt& other) const; // 小于运算符重载
bool operator<=(const MyInt& other) const; // 小于等于运算符重载
bool operator>(const MyInt& other) const; // 大于运算符重载
bool operator>=(const MyInt& other) const; // 大于等于运算符重载
MyInt& operator++(); // 前置自增运算符重载
MyInt operator++(int); // 后置自增运算符重载
MyInt& operator--(); // 前置自减运算符重载
MyInt operator--(int); // 后置自减运算符重载
private:
int m_value; // 对象的值
};
```
以上是一个简单的以int变量为对象的类,包含了对象的构造、拷贝、析构、赋值以及基本的加减乘除等运算符的重载,同时也包括了自增自减运算符的重载。