我迷失了这段代码,我需要为
做些什么Couple *pcouple1 = new Couple(mary, *pjohn);
Couple couple2(*pjane, mark);
上班?我在情侣(玛丽和情侣2)之间得到一个红色的波浪线(* pjane与以下信息:
*错误C2664:'情侣::情侣(常见情侣&)' :不能转换来自' Person' to' const char *'
*智能感知:没有构造函数的实例"情侣::情侣"匹配参数列表 参数类型是:(人,人)
代码是:
Class Couple&人
class Person {
char* name;
public:
friend class Couple;
friend ostream& operator<<(ostream& str, const Person& os)
{
str << os.name;
return str;
};
Person(const char* n)
{
name = (char*)n;
cout << "char constructor " << name << endl;
};
Person(const Person& os)
{
name = os.name;
cout << "Person constructor " << name << endl;
};
Person& operator=(const Person& os)
{
this->name = os.name;
return *this;
};
~Person()
{
free(name);
cout << "Class Person Destructor" << endl;
};
char* getName(){
return name;
};
};
class Couple {
Person *wife, *husband;
public:
friend ostream& operator<<(ostream& str, const Couple& p)
{
str << "He " << *p.husband << " She " << *p.wife;
};
Couple::Couple(const char* m, const char* z)
{
husband = new Person(m);
wife = new Person(z);
cout << "Couple1: " << endl;
};
Couple::Couple(const Couple& other)
{
husband = new Person(*other.husband);
wife = new Person(*other.wife);
cout << "Couple2: " << endl;
}
Couple& operator=(const Couple& other)
{
this->husband = new Person(*other.husband);
this->wife = new Person(*other.wife);
return *this;
};
~Couple()
{
free(husband->name);
free(husband);
free(wife->name);
free(wife);
cout << "Class Couple Destructor" << endl;
};
};
主要功能:
int main(void) {
Person *pjohn = new Person("John"),
*pjane = new Person("Jane");
Person mary("Mary"), mark("Mark");
Couple *pcouple1 = new Couple(mary, *pjohn);
Couple couple2(*pjane, mark);
delete pjohn;
delete pjane;
cout << *pcouple1 << endl;
cout << couple2 << endl;
couple2 = *pcouple1;
delete pcouple1;
cout << couple2 << endl;
return 0;
}
有人可以向我推荐一个好的来源/网站/书籍/练习来理解类似于这个练习的更好的功能指针,在此之前我还在学习。
答案 0 :(得分:1)
显然,您的Couple
构造函数需要两个char*
参数,但您正在尝试使用两个Couple
对象构造Person
对象。引入构造函数,接受Person
作为参数,或将给定的Person
实例转换为char*
。