C++ 如何使用私有构造函数C+测试私有成员+;
我有一些代码如下:C++ 如何使用私有构造函数C+测试私有成员+;,c++,unit-testing,googletest,C++,Unit Testing,Googletest,我有一些代码如下: class base{ private: base(); int x; public: friend class child; }; class child{ public: void display(base* b) { b->x = 1; } }; int main() { base* t; //t = new base; child c; c.display(t);
class base{
private:
base();
int x;
public:
friend class child;
};
class child{
public:
void display(base* b)
{
b->x = 1;
}
};
int main()
{
base* t;
//t = new base;
child c;
c.display(t);
}
我无法分配对象t
。我想测试x
的值。
如何测试此代码?您通常只测试类的公共API。
因此,如果需要测试
x
的值,则该值很可能也与其他类相关。您将child
声明为访问x
的朋友,这一事实支持这一事实
结论:将
x
公开或(更好)提供getter和setter方法。将此代码添加到公共部分的基类中:
friend int main();
然后在main函数中,取消注释以下行:
t=new base;
但我建议您将基类的构造函数设置为公共的,而不是私有的。另外,我真的很好奇为什么要将基类的构造函数设置为私有的。
base
没有接口,所以没有任何东西需要测试。您的测试应该验证child
是否按预期工作。因为我使用的是singleton类