我正在努力实现设计模板的工作。
第 62 行和第 63 行有错误。我不明白什么可能不是,因为我做了书中的所有内容。
在 main()
中运行的点:
C2440 Initialization: Unable to convert "Roma *" in "Human *" 62
C2440 Initialization: Unable to convert "Natasha *" in "Human *" 63
完整代码:
#include<iostream>
#include<string>
using namespace std;
class Human
{
public:
virtual string Sex() = 0;
};
class Male : public Human
{
public:
string Sex()
{
return "boy.\n";
}
};
class Female : public Human
{
public:
string Sex()
{
return "I'm wooman!\n";
}
};
class Gender
{
public:
virtual string DetermineTheSex() = 0;
};
class Natasha : public Gender
{
Human* $sex;
public:
Natasha(Human* obj) : $sex(obj) {}
string DetermineTheSex()
{
return "Natasha. " + $sex->Sex();
}
};
class Roma : public Gender
{
Human* $sex;
public:
Roma(Human* obj) : $sex(obj) {}
string DetermineTheSex()
{
return "Roma " + $sex->Sex();
}
};
int main() {
Human* mal = new Male();
Human* fem = new Female();
Human* Person1 = new Roma(mal); // <<<---- error
Human* Person2 = new Natasha(fem); // <<<---- error
delete mal;
delete fem;
return 0;
}
答案 0 :(得分:2)
class Gender
{
public:
virtual string DetermineTheSex() = 0;
};
class Natasha : public Gender
Roma
和 Natasha
继承了 Gender
,它不是 Human
的子类。
因此,您不能使用 Human*
来指向此类的对象。更改为 Gender*
它将起作用:
Gender* Person1 = new Roma(mal);
Gender* Person2 = new Natasha(fem);
更新:请不要在实际项目中使用 $
来命名变量,它可能会让人眼睛流血 ;-)