重载操作符
Overloading operator+ C++
我看到了多个关于如何添加同一个类的两个变量的例子,但是我找不到关于如何添加不同类的变量的例子。
如果它与我的问题相关,我们还没有使用模板,但我假设我们不允许使用它。
我想用+运算符将类book添加到类person。例:人;书b;p+b;//添加一本书,就像使用p. addbook (b)这样的函数一样;
class Person
{
private:
B * b;
string sName;
int numOfBook;
int maxNumOfBooks;
maxnummofbooks是允许携带的最大数目
public:
Person();
Person(const Person&);
~Person();
const Person operator = (const Person &)
void addBook(const Book &); //adds a book to a Person
Person operator+(Person );
Book getBook(){return b[numOfBook];}//returns index of book
};
Person::Person()
{
numOfBook = 0;
maxNumOfBooks = 10;
b = new B[maxNumOfBooks];
for(int x=0;x<maxNumOfBooks;x++)
{
设置name为"。我确实重载了这个
b[x] = "";
}
}
Person::Person(const Person& p)
{
numOfBook = p.numOfBook;
maxNumOfBooks = p.maxNumOfBooks;
b = new B[maxNumOfBooks];
for(int x=0;x<maxNumOfBooks;x++)
{
b[x] = p.b[x];
}
}
Person::~Person()
{
delete [] b;
}
void Person::addBook()
{
代替" if numOfBooks <maxNumOfBooks;>
是否编写了此代码。
}
Person Person::operator+(Person obj)
{
不完全确定这里该做什么。但我认为它应该是这样的。
Spell a;
++numOfBook;
a=this->getBook(numOfBook);
obj.addBook(a);
return *this;
}
const Person Person::operator = (const Person & obj)
{
delete [] b;
numOfBook = p.numOfBook;
maxNumOfBooks = p.maxNumOfBooks;
b = new B[maxNumOfBooks];
for(int x=0;x<maxNumOfBooks;x++)
{
b[x] = p.b[x];
}
return *this;
}
class Book
{
private:
string name;
int price;
public:
void setP();
int getP();
};
int main()
{
Person s;
Book bk("Story", 18);
s+bk;
我想在Person上添加一本书,但它也应该使用addBook()函数。
}
当您重载+
操作符时,您返回返回类型的新实例(对于算术类型,这通常是重载的,其中两个输入和输出是相同的类型,但这根本没有必要)。
你只需要弄清楚操作符应该做什么。在这种情况下,+
操作符应该将book添加到所调用的person对象的副本中(即返回一个新实例而不修改原始实例)。
Person Person::operator + (const Book& b){
Person tmp(*this); //create a copy of this Person to modify
tmp.addBook(b); //modify this new copy and not the original
return tmp; //return the modified copy
}
而+=
操作符将修改当前对象并返回一个引用
Person& Person::operator += (const Book& b){
addBook(b);
return *this;
}
如果您已经定义了+=
,您可以将+
操作符更改为:
Person Person::operator + (const Book& b){
return Person(*this) += b;
}
注意:
Person P;
Book B;
P + B; // P is not modified;
不等同于:
Person P;
Book B;
P.addBook(B); // P is modified
然而,下面是。
Person P;
Book B;
P += B; // P is modified
以及
Person P;
Book B;
P = P + B; // P is modified because it is assigned (P + B)