【发布时间】:2016-01-20 01:18:29
【问题描述】:
这是来自免费 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();
}
【问题讨论】:
-
从这里的函数声明中删除类限定符
Critter& Critter::operator=(const Critter& c);=>Critter& operator=(const Critter& c);。 -
我猜你的书期待 MS 编译器中的非标准编译器功能。
-
仍然无法编译。现在错误是错误:'op' 没有命名类型。下一个错误是: error: no 'void Critter::Greet() const' member function declaration in class 'Critter' 然后接下来的 7 个错误是这个重复错误: error: 'class Critter' has no member named '问候'
标签: c++ codeblocks