我的代码中有这个:
const Member & Member::operator=( const Member & rhs )
{
strcpy( this->firstName, rhs.firstName );
strcpy( this->lastName , rhs.lastName );
this->gender = rhs.gender;
this->year = rhs.year;
return *this;
}
由于某些原因,如果我使用它,它就不起作用。
它告诉我无法将Member
转换为Member&
我的老师在不同的课堂上以同样的方式和他的作品。我不明白为什么我认为签名是正确的,返回值也是如此。一些解释可能有所帮助谢谢
Member found;
found = vertices[0].find(set.familyHead); //returns a member
ERROR:
C:\Users\Kyle\Desktop\p4-2>make
g++ -ansi -Wno-reorder -Wall -g -c familyRunner.cpp
g++ -ansi -Wno-reorder -Wall -g -c familytree.cpp
familytree.cpp: In member function 'void FamilyTree::findSet(FamilySet&)':
familytree.cpp:26:8: error: no match for 'operator=' (operand types are 'Member'
and 'Member')
found = vertices[0].find(set.familyHead);
^
familytree.cpp:26:8: note: candidate is:
In file included from familytree.h:6:0,
from familytree.cpp:1:
Member.h:19:17: note: const Member& Member::operator=(Member&)
const Member & operator=( Member & rhs );
^
Member.h:19:17: note: no known conversion for argument 1 from 'Member' to 'Member&'
Makefile:8: recipe for target 'familytree.o' failed
make: *** [familytree.o] Error 1
老师的签名:
const string & operator= ( const string & rhs ); // Copy
答案 0 :(得分:3)
您很可能尝试使用右值,如下所示:
A a;
a = A();
如果是这种情况,临时无法绑定到非const引用。因此,错误。您可以将更常规的签名用于复制赋值运算符,其中参数为const A&
。您可能想要做的另一件事是将返回类型更改为A&
,以允许操作员链接。例如:
A a;
A b;
A c;
a = b = c;
最后,我建议您查看我们自制的常见问题解答What is the copy-and-swap idiom?
常见问题解答详细介绍,但目前您的副本分配操作员没有解决两个主要问题:
理想情况下,您应该只关注Rule of zero并使用std::string
数据成员。如果您不过度手动实现特殊成员函数,您的课程将自动执行正确的操作。