C++运算符重载方法
我正在做一些家庭作业,并且在如何形成用于重载类成员的方法签名方面遇到问题。
我的头文件
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
}
当我尝试编译代码时,我收到一条错误,提示
ex4.cpp:42: error: invalid initialization of reference of type ‘const MyInt&’
from expression of type ‘MyInt* const’
我在理解如何使其工作时遇到问题,并尝试了一些方法签名。在我的教科书中,它们排列了所有重载,但我希望找出我做错了什么,而不是仅仅按照流程来编译我的代码。
谢谢!
I'm working through some home work and having problems with how to form my method signature for overloading a member of a class.
My header file
class MyInt
{
int internalInt;
public:
MyInt::MyInt(int i);
const MyInt operator+(const MyInt& mi);
const MyInt& operator++();
};
My code file
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
}
When I try to compile the code I'm getting an error that says
ex4.cpp:42: error: invalid initialization of reference of type ‘const MyInt&’
from expression of type ‘MyInt* const’
I'm having problems understanding how to get this working and have tried a few method signatures. In my text book they are in lining all the overloads but I was hoping to figure out what I'm doing wrong instead of just going with the flow to get my code to compile.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试:
您返回的是 this 指针,而不是引用,您需要取消引用它。
try:
You are returning the this pointer, not the reference, you need to dereference it.
首先,在
operator++()
中,编写return *this;
而不是return this;
。还要删除 const!-
其次,将其设为 const-function,因为
这是 const-function。没有它,您将无法添加 MyInt 的 const 对象。
在最右边写上
const
后,你可以这样写:First of all, in
operator++()
, writereturn *this;
instead ofreturn this;
. Also remove the const!-
Second, Make it const-function, as
This is const-function. Without it, you would not be able to add const objects of MyInt.
After you write
const
on the right most side, you can write this: