C++Friend构造函数
C++ Friend constructor
我有两个类:Point
,它只存在于Space
中
class Point
{
private:
Point(const Space &space, int x=0, int y=0, int z=0);
int x, y, z;
const Space & m_space;
};
构造函数是故意私有的,我不想直接调用它。我想用这种方式创建点
Space mySpace;
Point myPoint = mySpace.Point(5,7,3);
有什么办法吗?谢谢
是,将Space::Point()
声明为友元方法。该方法将接收对Point
的私有成员的访问权限。
class Point
{
public:
friend Point Space::Point(int, int, int);
private:
// ...
我会这样做:
class Space
{
public:
class Point
{
private:
Point(const Space &space, int x=0, int y=0, int z=0);
int m_x, m_y, m_z;
const Space & m_space;
friend class Space;
};
Point MakePoint(int x=0, int y=0, int z=0);
};
Space::Point::Point(const Space &space, int x, int y, int z)
: m_space(space), m_x(x), m_y(y), m_z(z)
{
}
Space::Point Space::MakePoint(int x, int y, int z)
{
return Point(*this, x, y, z);
}
Space mySpace;
Space::Point myPoint = mySpace.MakePoint(5,7,3);
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 具有默认模板类型的默认构造函数的类型推导
- 无法访问Friend类的私有构造函数
- C++Friend构造函数
- 使Friend成为模板类的构造函数