使第二个类的构造函数成为第一个类中的友元函数
Making constructor of a second class a friend function in the first class
我有两个类,名称为firstClass和secondClass。我设法让二等朋友成为一等舱的朋友。我现在尝试只将 secondClass 构造函数作为朋友,而不是整个类。首先,我收到错误:"secondClass"没有命名类型,并且尝试使用前向声明修复它会产生错误:无效使用不完整的类型"类 secondClass"。 有没有可能让二等建筑商成为头等舱的朋友。
#include <iostream>
using namespace std;
/*
//these forward declaration, do not solve the problem
class firstClass;
class secondClass;
secondClass::secondClass(const firstClass& fc);
*/
class firstClass
{
private:
int value;
friend secondClass::secondClass(const firstClass& fc);
//friend class secondClass; //this works
public:
firstClass(int val = 0): value(val){}
};
class secondClass
{
public:
secondClass(int val = 0): value(val){}
secondClass(const firstClass& fc)
{
value = fc.value;
}
int getValue()
{
return value;
}
int value;
};
int main()
{
firstClass fc(5);
secondClass sc(fc);
cout<<sc.value;
}
以下是执行前向声明的正确方法:
//secondClass needs to know the type firstClass exists to take it as an argument to the ctor
class firstClass;
class secondClass
{
public:
secondClass(int val = 0): value(val){}
secondClass(const firstClass& fc); //Just declare that this function exists
int getValue()
{
return value;
}
int value;
};
class firstClass
{
private:
int value;
//Since this function is declared, this works
friend secondClass::secondClass(const firstClass& fc);
public:
firstClass(int val = 0): value(val){}
};
//Finally, now that firstClass is implemented, we can implement this function
secondClass::secondClass(const firstClass& fc)
{
value = fc.value;
}
在这里看到它运行:https://ideone.com/ZvXIpw
相关文章:
- C++模板来检查友元函数的存在
- 如何使用单独文件中的派生类访问友元函数对象
- 模板化的类和友元函数
- 友元函数无法访问私有数据成员 (c++)
- 继承和友元函数,从基类访问受保护的成员
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- 在模板类之外定义友元函数的正确方法是什么?
- 2个模板化类的非模板友元函数未定义引用错误
- C++ 友元函数和私有构造函数
- 使第二个类的构造函数成为第一个类中的友元函数
- 未定义的类模板不会实例化以检查友元函数
- C++类中的友元函数有问题?
- 使用typedef'ed返回类型声明友元函数时出现编译器错误
- 模板类中的模板友元函数
- C++ 17 个友元函数声明和内联命名空间
- 友元函数需要一个帮助程序函数
- 在类内定义的友元函数与类外定义的友元函数的查找规则之间的差异
- 运算符重载在 C++ 中使用友元函数
- 类C++友元函数无法访问封装的类
- 函数指针作为友元函数