使第二个类的构造函数成为第一个类中的友元函数

Making constructor of a second class a friend function in the first class

本文关键字:友元 函数 第一个 第二个 构造函数      更新时间:2023-10-16

我有两个类,名称为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