从书籍中复制的代码无法编译。已弃用或错别字?
Code copied from a book won't compile. Deprecated or typo?
这是一个来自免费c++电子书的程序,但它无法编译。一开始我把它打出来,但意识到它无法编译,我试着直接从电子书中复制到代码块13.12中。它仍然无法编译。这本电子书是2010年出版的,所以可能代码不符合当前标准,或者在某个地方有语法错别字。请帮我找出问题所在。
错误是:
error: extra qualification 'Critter::' on member 'operator=' [-fpermissive]|
代码是:
#include <iostream>
using namespace std;
class Critter
{
public:
Critter(const string& name = "", int age = 0);
~Critter(); //destructor prototype
Critter(const Critter& c); //copy constructor prototype
Critter& Critter::operator=(const Critter& c);
op
void Greet() const;
private:
string* m_pName;
int m_Age;
};
Critter::Critter(const string& name, int age)
{
cout << "Constructor calledn";
m_pName = new string(name);
m_Age = age;
}
Critter::~Critter() //destructor definition
{
cout << "Destructor calledn";
delete m_pName;
}
Critter::Critter(const Critter& c) //copy constructor definition
{
cout << "Copy Constructor calledn";
m_pName = new string(*(c.m_pName));
m_Age = c.m_Age;
}
Critter& Critter::operator=(const Critter& c)
{
cout << "Overloaded Assignment Operator calledn";
if (this != &c)
{
delete m_pName;
m_pName = new string(*(c.m_pName));
m_Age = c.m_Age;
}
return *this;
}
void Critter::Greet() const
{
cout << "I’m " << *m_pName << " and I’m " << m_Age << " years old.n";
cout << "&m_pName: " << cout << &m_pName << endl;
}
void testDestructor();
void testCopyConstructor(Critter aCopy);
void testAssignmentOp();
int main()
{
testDestructor();
cout << endl;
Critter crit("Poochie", 5);
crit.Greet();
testCopyConstructor(crit);
crit.Greet();
cout << endl;
testAssignmentOp();
return 0;
}
void testDestructor()
{
Critter toDestroy("Rover", 3);
toDestroy.Greet();
}
void testCopyConstructor(Critter aCopy)
{
aCopy.Greet();
}
void testAssignmentOp()
{
Critter crit1("crit1", 7);
Critter crit2("crit2", 9);
crit1 = crit2;
crit1.Greet();
crit2.Greet();
cout << endl;
Critter crit3("crit", 11);
crit3 = crit3;
crit3.Greet();
}
正如消息所说,
中有一个额外的Critter::
Critter& Critter::operator=(const Critter& c);
由于这是在类声明中,所以它必须是类的成员,不需要以类名作为前缀。
Critter& operator=(const Critter& c);
是正确的形式。
类名前缀仅在类之外定义成员时使用,如示例后面的代码。
从操作符原型中删除Critter::