#include<iostream>
using namespace std;
//定义一个整形类
class MyInteger
{
//重载"<<"运算符用来输出类对象
friend ostream& operator<<(ostream& cout, MyInteger& myint);
private:
int m_Integer;
public:
MyInteger();
MyInteger(MyInteger& mi)
{
m_Integer = mi.m_Integer;
}
//前置++运算符
//返回值为引用,也就是对象本身
MyInteger& operator++()
{
m_Integer++;
return *this;
}
//后置++运算符
//返回值为类类型,因为返回的是自增前记录的值,temp是局部变量
MyInteger& operator++(int)//加上一个占位参数,用来区分前置自增和后置自增
{
//记录当前的值
MyInteger * temp = new MyInteger(*this);
//使数据成员自增
temp->m_Integer++;
//返回此前记录的值
return *temp;
}
};
//定义构造函数
MyInteger::MyInteger() :m_Integer(10)
{
}
//重载"<<"运算符
ostream& operator<<(ostream& cout, MyInteger& myint)
{
cout << myint.m_Integer;
return cout;
}
void test_1()
{
MyInteger myint;
cout << ++myint << endl;//这两行
cout << myint << endl; //可以正常输出
MyInteger myint2;
cout << myint2++<< endl;//这个地方报错,提示我没有这些操作数匹配的"<<"运算符为什么
}
int main()
{
test_1();
system("pause");
return 0;
}
C++ 运算符重载 代码报错问题
10
```#include<iostream>
using namespace std;
//定义一个整形类
class MyInteger
{
//重载"<<"运算符用来输出类对象
friend ostream& operator<<(ostream& cout, MyInteger& myint);
private:
int m_Integer;
public:
MyInteger();
//前置++运算符
//返回值为引用,也就是对象本身
MyInteger& operator++()
{
m_Integer++;
return *this;
}
//后置++运算符
//返回值为类类型,因为返回的是自增前记录的值,temp是局部变量
MyInteger operator++(int)//加上一个占位参数,用来区分前置自增和后置自增
{
//记录当前的值
MyInteger temp = *this;
//使数据成员自增
m_Integer++;
//返回此前记录的值
return temp;
}
};
//定义构造函数
MyInteger::MyInteger() :m_Integer(10)
{
}
//重载"<<"运算符
ostream& operator<<(ostream& cout, MyInteger& myint)
{
cout << myint.m_Integer;
return cout;
}
void test_1()
{
MyInteger myint;
cout << ++myint << endl;//这两行
cout << myint << endl; //可以正常输出
MyInteger myint2;
cout << myint2++<< endl;//这个地方报错,提示我没有这些操作数匹配的"<<"运算符为什么
}
int main()
{
test_1();
system("pause");
return 0;
}
我用的VS2019
- 点赞
- 写回答
- 关注问题
- 收藏
- 复制链接分享
- 邀请回答
2条回答
为你推荐
- c++重载输出流运算符
- 其他
- 2个回答
- C++友元函数不能访问私有变量问题
- c++
- 1个回答
- c++重载输出运算符,输出运算符后接函数的返回值为什么会报错“没有与操作数匹配的运算符”?
- c++
- 1个回答
- C++ 运算符重载 代码报错问题
- c++
- 2个回答
- VS2019 C++ 重载‘+’,‘=’后不能正确的把相加后的表达式赋值给新创建的类。
- 用其他类的对象做参数,重载+号运算符,vc2010报错:没有与指定类型匹配的operator+重载函数
- c++
- 2个回答
- 为什么重载后置递增运算符用左移运算符重载输出时左移运算符重载函数形参不能用引用?
- c++
- 1个回答
- 请问一下,在vs2019c++里面,这段代码总是报LNK2019的错误。
- c++
- 1个回答
- C++代码运行中出现无法解析的外部命令?
- c++
- 3个回答
- operator new是普通函数还是重载new运算符的函数
- c++
- 1个回答
- C++运算符重载的问题...
- 运算符重载之后,析构函数报错,怎么改?顺便说一下原因,谢谢
- 临时对象到底是不是对象,为什么我的代码会出错?c++
- c++
- 3个回答
- 关于C++编译时的报错,求帮忙指出?
- 编译器
- c++
- 1个回答
- 一个关于C++运算符重载的问题
- 2个回答
- C++一个小程序,关于运算符重载,无法运行,不知道哪里出错。
- 2个回答
- 重载运算符类型不匹配
- 2个回答
- c++中运算符重载 这个小程序怎么不对呢