Google Mock:“没有合适的默认构造函数可用”?
将 Visual Studio 2010 C++ 与 googlemock 结合使用。我正在尝试使用我创建的模拟,但出现编译器错误:
EmployeeFake employeeStub;
错误是:
1>c:\someclasstests.cpp(22): error C2512: 'MyNamespace::EmployeeFake' : no appropriate
default constructor available
EmployeeFake:
class EmployeeFake: public Employee{
public:
MOCK_CONST_METHOD0(GetSalary,
double());
}
Employee:
class Employee
{
public:
Employee(PensionPlan *pensionPlan, const char * fullName);
virtual ~Employee(void);
virtual double GetSalary() const;
}
我认为问题是基类没有默认构造函数,但应该如何我修好这个吗?我需要向我的基类添加默认构造函数吗?或者我需要向我的模拟类添加一个构造函数吗?还是别的什么?
Using Visual Studio 2010 C++ with googlemock. I'm trying to use a mock I created and I'm getting the compiler error on the line:
EmployeeFake employeeStub;
The error is:
1>c:\someclasstests.cpp(22): error C2512: 'MyNamespace::EmployeeFake' : no appropriate
default constructor available
EmployeeFake:
class EmployeeFake: public Employee{
public:
MOCK_CONST_METHOD0(GetSalary,
double());
}
Employee:
class Employee
{
public:
Employee(PensionPlan *pensionPlan, const char * fullName);
virtual ~Employee(void);
virtual double GetSalary() const;
}
I gather that the problem is that the base class doesn't have a default constructor but how should I fix this? Do I need to add a default constructor to my base class? Or do I need to add a constructor to my mock class? Or something else?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只需将一个构造函数添加到您的模拟中,该构造函数委托给 Employee 构造函数:
然后像构造 Employee 一样构造 MockEmployee。然而,我强烈建议您对这段代码进行一些改进,这将简化这一过程:
因此,为了澄清,我的建议是:
You can just add a constructor to your mock that delegates to the Employee constructor:
Then construct MockEmployee like you would construct Employee. However, there are a couple things that can be improved about this code that I would highly recommend and that would simplify this:
So, to clarify, my recommendation would be:
您已经提出了一个可能的答案,但让我们阐明一些选项:
1)使基础默认可构造。最简单的方法是提供默认参数:(
请注意,我们说“显式”以避免来自
PensionPlan*
的默认转换。)2) 在派生类的构造函数的基初始化列表中调用构造函数:
2a) 给
EmployeeFake
一个适当的构造函数并将其传递:(请注意,(1) 是声明,而 (2) 和 (2a) 是定义。)
You've already suggested a possible answer, but let's spell out some options:
1) Make the base default-constructible. Easiest to do by providing default arguments:
(Note that we say
explicit
to avoid tacit conversions fromPensionPlan*
.)2) Call the constructor in the derived class's constructor's base initializer list:
2a) Give
EmployeeFake
an appropriate constructor and pass it on:(Note that (1) is a declaration, while (2) and (2a) are the definitions.)