如何从它的私有构造函数访问 class 的私有成员
How to access private members of a class from it's private constructor
我有以下 class,这里我正在尝试从私有构造函数访问 class 的私有成员。
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;
}
}
我收到以下错误消息
Severity Code Description Project File Line Suppression State
Error C2248 'House::House': cannot access private member declared in class 'House' TestC++ c:\program files (x86)\microsoft visual studio17\community\vc\tools\msvc.14.26428\include\memory 1770
因为 House
没有 public 构造函数,class 之外的代码不允许构造 House
。但你正试图做到这一点,在这里:
House::house = std::make_shared<House>();
std::make_shared
的实现调用new
构造一个新的House
,但是std::make_shared
无法访问House
的私有构造函数。要修复它,您需要自己构建 House
:
House::house.reset(new House);
我有以下 class,这里我正在尝试从私有构造函数访问 class 的私有成员。
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;
}
}
我收到以下错误消息
Severity Code Description Project File Line Suppression State Error C2248 'House::House': cannot access private member declared in class 'House' TestC++ c:\program files (x86)\microsoft visual studio17\community\vc\tools\msvc.14.26428\include\memory 1770
因为 House
没有 public 构造函数,class 之外的代码不允许构造 House
。但你正试图做到这一点,在这里:
House::house = std::make_shared<House>();
std::make_shared
的实现调用new
构造一个新的House
,但是std::make_shared
无法访问House
的私有构造函数。要修复它,您需要自己构建 House
:
House::house.reset(new House);