【发布时间】:2021-08-06 17:20:47
【问题描述】:
我看到很多类似的帖子,例如this one,但没有一个能解决我的问题。
我有 2 个班级,Cache 和 Reader:
Cache.hpp
class Cache {
public:
explicit Cache(unsigned int max_files);
private:
size_t max_size;
Cache.cpp
Cache::Cache(unsigned int max_files): max_files(max_files) {}
Reader.hpp
class Reader{
public:
Reader(unsigned int num_files = 4);
private:
mutable Cache my_cache;
Reader.cpp
Reader::Reader(unsigned int num_files){
if (num_files > 10){
num_files = 10;
}
my_cache(num_files);
}
在编译时,我得到这个错误:
In constructor ‘Reader::Reader(unsigned int)’: error: no matching function for call to ‘Cache::Cache()’
16 | Reader::Reader(unsigned int num_files) {
note: candidate: ‘Cache::Cache(unsigned int)’
26 | explicit Cache(unsigned int max_files);
【问题讨论】:
-
您的成员初始化语法错误。应该是
Reader::Reader(unsigned int num_files) : my_cache(num_files) { } -
更改阅读器::Reader(unsigned int num_files){ my_cache(num_files); } to Reader::Reader(unsigned int num_files) : my_cache(num_files){ } 原因是您需要初始化 Cache,但在创建 Reader 类之前需要它,因为您没有默认构造函数(即缓存())。
-
那不是像做
my_cache = num_files,而不是调用Cache构造函数吗? -
@DanielCJacobs 您在问题中链接到的答案——您为什么不尝试接受的答案?那会解决你的问题。
-
@PaulMcKenzie 哦,看来我只是没有正确理解成员初始化的工作原理;因此我之前的评论