這是一個免費的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 called\n";
m_pName = new string(name);
m_Age = age;
}
Critter::~Critter() //destructor definition
{
cout << "Destructor called\n";
delete m_pName;
}
Critter::Critter(const Critter& c) //copy constructor definition
{
cout << "Copy Constructor called\n";
m_pName = new string(*(c.m_pName));
m_Age = c.m_Age;
}
Critter& Critter::operator=(const Critter& c)
{
cout << "Overloaded Assignment Operator called\n";
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();
}
取下函數聲明這裏的類限定符'小動物和小動物::運算符=(const的小動物& c);'=>'小動物運算符=(const的小動物& c);'。 –
I」 m猜測你的書正在期待MS編譯器中的非標準編譯器功能 –
仍然不編譯,現在錯誤是錯誤的:'op'沒有命名一個類型,而下一個錯誤是:error:no'void在'Critter'類中聲明的Critter :: Greet()const'成員函數接下來的7個錯誤是這個重複錯誤:錯誤:'class Critter'沒有名爲'Greet'的成員 –