函数指针,错误无法将参数 1 转换为常量字符
Function Pointers, error cannot convert argument 1 to const char
我迷失了这段代码,我需要做什么
Couple *pcouple1 = new Couple(mary, *pjohn);
Couple couple2(*pjane, mark);
上班?我在夫妇(玛丽和夫妇2(*pjane与以下信息:
*错误 C2664:"耦合::耦合(常量耦合 &)":无法将参数 1 从"人"转换为"常量字符 *"
*智能感知:构造函数"Couple::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;
}
有人可以向我推荐一个好的资源/站点/书籍/练习,以更好地理解与此练习类似的函数指针,提前感谢我还在学习。
显然,您的Couple
构造函数需要两个char*
参数,但您正在尝试使用两个Person
对象构造Couple
对象。要么引入构造函数,它将接受Person
作为参数,要么将给定的Person
实例转换为char*
。
相关文章:
- 是否应避免从非常量迭代器转换为常量迭代器?
- 是否有内置方法可以强制转换为不同的基础类型,但保留常量限定符?
- 为什么我收到"从常量指针到指针的转换无效?
- 从'size_t'转换为"常量双倍",可能会丢失数据
- 在编译时将常量字符* 转换为常量 char_type*
- 为什么下面带有非常量转换函数的代码没有歧义?
- 错误:请求从"常量字符 [5]"转换为非标量类型"字符串"
- 字符串强制转换为常量字符*
- 为什么我可以隐式地将字符*转换为常量字符*,但不能将无符号字符*
- 将错误作为从字符串常量到"char*"的已弃用转换 [-Wwrite-strings]
- 将编译时常量向量转换为堆分配版本
- 在<uint8_t> <char> c++ 中将常量向量转换为常量向量
- 在不同类型之间转换常量指针
- 转换(常量字符*)变量出错
- C++大小写中的类型转换常量字符串
- 转换常量无符号字符无效
- 转换常量表达式定义的说明
- c++ 11强制转换常量迭代器,指向shared_ptr对象的容器
- 条件运算符+上转换+常量引用
- c++限定转换-常量和模板