如何从类的私有构造函数访问类的私有成员



我有下面的类,在这里我试图从私有构造函数访问该类的私有成员。

class House {
private:
int len;
int wid;
House()
{
}
public:
~House() 
{
std::cout << "destructor call" << std::endl;
}
static std::shared_ptr<House> house;
static auto getHouse(const int length, const int width);
void setlen(int lenth) { len = lenth; }
void setwid(int width) { wid = width; }
int getlen() { return len; }
int getwid() { return wid; }
};
auto House::getHouse(const int length, const int width)
{
House::house = std::make_shared<House>();
if ((House::house->getlen()==length) && (House::house->getwid()== width)) 
{
return House::house;
}
else
{
House::house->setlen(length);
House::house->setwid(width);
return House::house;
}
}

我收到以下错误消息

严重性代码描述项目文件行禁止显示状态错误C2248"House::House":无法访问类"House"中声明的私有成员TestC++c:\program files(x86(\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\memory 1770

因为House没有公共构造函数,所以不允许类外的代码构造House。但你正试图做到这一点,在这里:

House::house = std::make_shared<House>();

std::make_shared的实现调用new来构造新的House,但std::make_shared不能访问House的私有构造函数。要修复它,您需要自己构建House

House::house.reset(new House);

最新更新