我有以下课程,在这里我试图从私有构造函数访问该类的私有成员。
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
答案 0 :(得分:2)
由于House
没有公共构造函数,因此不允许类外的代码构造House
。但是,您正在尝试做到这一点,
House::house = std::make_shared<House>();
std::make_shared
的实现调用new
来构造新的House
,但是std::make_shared
无法访问House
的私有构造函数。要解决此问题,您需要自己构建House
:
House::house.reset(new House);