问题描述
我创建了一个Fraction类,该类具有用于在两个Fraction对象之间进行加,减,乘和除的成员函数,以及所需的默认构造函数和复制构造函数.
I created a Fraction class that is has member functions to add, subtract, multiply, and divide between two Fraction Objects along with the required default and copy constructors.
对于这个问题,我必须使用指针(不能使用向量!),因为只有用户选择才能创建Fraction对象.简而言之,指针声明和新的初始化在不同的范围内.
For this problem, I must used pointers (cannot use vectors!) because the Fraction objects can only be created if the user chooses to. In short, the pointer declaration and new initialization are in difference scopes.
我也在尝试重载operator =,operator +,operator-,operator *和operator/来接受类似以下内容的东西.
I am trying to also overload the operator=, operator+, operator-, operator*, and operator/ to accept something like the following.
Fraction* fr1 = new Fraction(1,2);
Fraction* fr2 = new Fraction(3,4);
Fraction* fr3 = new Fraction();
fr3 = fr1 + fr2;
我当前的重载operator =成员函数如下:
My current overloaded operator= member function looks like so:
Fraction* Fraction::operator=(const Fraction*& fr) {
num = fr->num;
denom = fr->denom;
return this;
}
Fraction* Fraction::operator+(const Fraction*& fr) const {
int gcd = gcdRecurEuclid(num * fr->denom + denom * fr->num, denom * fr->denom);
Fraction* temp;
temp = new Fraction((num * fr->denom + fr->num * denom) / gcd,
(denom * fr->denom) / gcd);
return temp;
}
我一直收到错误'+':无法添加两个指针,这很可能意味着我的重载运算符+没有正确写入(和/或我的重载赋值运算符).我需要做些什么来纠正这个问题?同样,我的讲师希望我使用指针,而不希望我传递或返回任何内容的副本.我要么需要通过引用传递(或通过指针传递?类似的东西?).
I keep getting the error '+' : cannot add two pointers, which most likely means my overloaded operator+ is not written correctly (and/or my overloaded assignment operator).What do I need to do to correct this? Again, my instructor wants me to work with pointers, and does not want me to pass nor return copies of anything. I either need to pass by reference (or pointer? similar thing?).
推荐答案
您已经发现,尝试对指针使用算术运算符将导致编译器尝试执行指针算术.要在指针上调用您自己的重载运算符,您可以执行以下操作
As you've discovered, trying to use arithmetic operators on pointers will result in the compiler trying to do pointer arithmetic. To call your own overloaded operator on a pointer, you can either do
Fraction *f, *g; // allocated with new
f->operator+(*g); /// Urgh!
或者几乎是丑陋的
Fraction *f, *g;
(*f) + (*g);
使它变得更好一点的一种简单方法是声明三个新的参考变量,如下所示:
One easy way to make this a bit nicer is to declare three new reference variables like this:
Fraction& f1 = *pfr1;
Fraction& f2 = *pfr2;
Fraction& f3 = *ptr3;
pfrN
是指向分数的指针.现在,如果您使用引用变量,则将正确调用重载的运算符,并且无需放入所有多余的星号.这些引用将在范围的结尾消失,并且可能不会在程序中使用任何额外的内存.您仍然需要delete
原始指针!
Where the pfrN
s are the pointers to your fractions. Now if you use the reference variables, your overloaded operators will be called correctly, and you don't need to put in all the extra asterisks. The references will disappear at the end of the scope, and probably won't use any extra memory in your programme. You still need to delete
the original pointers though!
这篇关于运算符重载:无法添加两个指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!