当我尝试模拟一个函数时,我得到了一些奇怪的编译错误。 编译器抱怨复制构造函数。
代码段:
class db_key {
public:
db_key(void) {}
explicit db_key(const char* buf) {}
~db_key(void) {}
};
class bar_A {
public:
explicit bar_A(const db_key& key): m_key(key) {}
virtual ~bar_A(void) {}
const db_key& dbkey(void) const { return m_key; }
private:
const db_key m_key;
};
class bar_B: bar_A {
public:
explicit bar_B(const db_key& key): bar_A(key) {}
virtual int read(int index) const { return index; }
};
class accessor_c {
public:
static const char* name(void) { return "general_accessor"; }
static accessor_c instance(const char* _db_name)
{
return accessor_c(_db_name);
}
virtual ~accessor_c(void) {}
const bar_B mem;
virtual const bar_B& get_bar_B_mem(void) const
{
return mem;
}
protected:
explicit accessor_c(const char* _db_name):
mem(db_key("foo")), m_db_name(_db_name) {}
private:
const char* const m_db_name;
};
inline accessor_c accessor(const char* db_name)
{
return accessor_c::instance(db_name);
}
模拟:
class mock_accessor_c : public accessor_c {
public:
explicit mock_accessor_c(const char* _db_name):
accessor_c(_db_name) {}
virtual ~accessor_c(void) {}
static mock_accessor_c instance(const char* _db_name)
{
return mock_accessor_c(_db_name);
}
MOCK_CONST_METHOD0(get_bar_B_mem, const bar_B&(void));
};
int main(int argc, char** argv) {
::testing::InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}
我无法破译我收到的错误消息......这是:
In file included from /usr/include/gtest/internal/gtest-internal.h:40:0,
from /usr/include/gtest/gtest.h:57,
from mock.cpp:1:
/usr/include/gmock/gmock-spec-builders.h: In copy constructor ‘testing::internal::FunctionMocker<const bar_B&()>::FunctionMocker(const testing::internal::FunctionMocker<const bar_B&()>&)’:
/usr/include/gmock/gmock-spec-builders.h:1728:3: error: ‘testing::internal::FunctionMockerBase<F>::FunctionMockerBase(const testing::internal::FunctionMockerBase<F>&) [with F = const bar_B&()]’ is private
GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase);
^
In file included from /usr/include/gmock/gmock.h:61:0,
from mock.cpp:2:
/usr/include/gmock/gmock-generated-function-mockers.h:61:7: error: within this context
class FunctionMocker<R()> : public
^
mock.cpp: In copy constructor ‘mock_accessor_c::mock_accessor_c(const mock_accessor_c&)’:
mock.cpp:55:7: note: synthesized method ‘testing::internal::FunctionMocker<const bar_B&()>::FunctionMocker(const testing::internal::FunctionMocker<const bar_B&()>&)’ first required here
class mock_accessor_c : public accessor_c {
^
mock.cpp: In static member function ‘static mock_accessor_c mock_accessor_c::instance(const char*)’:
mock.cpp:62:37: note: synthesized method ‘mock_accessor_c::mock_accessor_c(const mock_accessor_c&)’ first required here
return mock_accessor_c(_db_name);
^
提前致谢。
答案 0 :(得分:3)
简短的回答是模拟对象不可复制,因此关于私有构造函数的编译器错误。基于对代码的快速目视检查,mock_accessor_c :: instance()方法导致此错误,因为它按值返回模拟,从而进行复制。
我建议完全删除mock_accessor_c :: instance()方法,而是在需要时直接构造mock。