C++ C++;运算符重载方法
我正在做一些家庭作业,在如何形成重载类成员的方法签名方面遇到了问题 我的头文件C++ C++;运算符重载方法,c++,operator-overloading,C++,Operator Overloading,我正在做一些家庭作业,在如何形成重载类成员的方法签名方面遇到了问题 我的头文件 class MyInt { int internalInt; public: MyInt::MyInt(int i); const MyInt operator+(const MyInt& mi); const MyInt& operator++(); }; 我的代码文件 MyInt::MyInt(int i) { internalInt = i; } co
class MyInt
{
int internalInt;
public:
MyInt::MyInt(int i);
const MyInt operator+(const MyInt& mi);
const MyInt& operator++();
};
我的代码文件
MyInt::MyInt(int i)
{
internalInt = i;
}
const MyInt MyInt::operator+(const MyInt& mi)
{
cout << "Inside the operator+\n";
mi.print(cout);
return MyInt(internalInt + mi.internalInt);
}
const MyInt& MyInt::operator++()
{
cout << "Inside the operator++\n";
internalInt++;
return this; //Line 42
}
我在理解如何使其工作时遇到问题,并且尝试了一些方法签名。在我的课本中,他们在排列所有的重载,但我希望找出我做错了什么,而不是仅仅按照流程让我的代码编译
谢谢 试试看:
const MyInt& MyInt::operator++()
{
cout << "Inside the operator++\n";
internalInt++;
return *this;
}
const MyInt&MyInt::operator++()
{
试试看:
const MyInt&MyInt::operator++()
{
cout首先,在operator++()
中,编写return*this;
而不是returnthis;
。同时删除常量
-
第二,将其设置为const函数,如下所示
const MyInt MyInt::operator+(const MyInt& mi) const // <--- note this!
首先,在operator++()
中,编写return*this;
而不是returnthis;
。同时删除常量
-
第二,将其设置为const函数,如下所示
const MyInt MyInt::operator+(const MyInt& mi) const // <--- note this!
你能指出哪一行是原始源文件中的第42行吗?你能指出哪一行是原始源文件中的第42行吗?所以基本上我不应该返回常量,因为返回对象应该是可变的(有意义的)但是,如果我们不改变方法中的值,那么我就应该接受一个常量的论点。@ Mike:完全正确。而且,在最右边的写<代码> const 使<代码>这个< /Cult>指针const。返回对象确实不应该是可变的,因为原始类型的临时变量是不可变的。请考虑<代码> a=(b+c)。=d;
这将不允许int
,但允许MyInt
使用,除非操作符+
的返回值是const
。因此基本上我不应该返回const,因为返回对象应该是可变的(有意义的)但是,如果我们不改变方法中的值,那么我就应该接受一个常量的论点。@ Mike:完全正确。而且,在最右边的写<代码> const 使<代码>这个< /Cult>指针const。返回对象确实不应该是可变的,因为原始类型的临时变量是不可变的。请考虑<代码> a=(b+c)。=d;
这不允许用于int
,但允许用于MyInt
,除非运算符+
的返回值为常量。
const MyInt MyInt::operator+(const MyInt& mi) const // <--- note this!
const MyInt m1(10);
MyInt m2(20);
MyInt m3 = m1 + m2 ; //m1 is const, so it can call ONLY const-function