你能检查一下这段代码吗:
#include <vector>
class A
{
public:
A(int a, int b);
};
class C :public A
{
public:
C(int a, int b):A(a,b){}
static C instances;
};
C C::instances;
int main()
{
return 1;
}
编译给我的错误是:
$ c++ inheritance.cpp inheritance.cpp:16:6: error: no matching function for call to ‘C::C()’ inheritance.cpp:16:6: note: candidates are: inheritance.cpp:12:2: note: C::C(int, int) inheritance.cpp:12:2: note: candidate expects 2 arguments, 0 provided inheritance.cpp:8:7: note: C::C(const C&) inheritance.cpp:8:7: note: candidate expects 1 argument, 0 provided
我需要 C 从 A 继承,我需要 A 在其构造函数中有参数。 最后,我需要在不带参数的情况下声明和定义实例的静态变量。 那么有解决办法吗?我很重视您的宝贵意见。
还有一点需要注意: 如果静态变量是一个容器,例如:
static std::vector instances;
代码会编译得很好。为什么?
编辑:
感谢大家的回答,
但是,如果我将 C C::instances;
修改为 C C::instances(0,0);
我会得到另一个错误:
$ C++ 继承.cpp
/tmp/cctw6l67.o: 在函数 C::C(int, int)' 中:
inheritance.cpp:(.text._ZN1CC2Eii[_ZN1CC5Eii]+0x1b): undefined reference
A::A(int, int)'
collect2: ld 返回 1 个退出状态
知道为什么吗?以及如何解决?
谢谢
最佳答案
如果您定义一个构造函数,编译器将不再为您生成一个默认的构造函数,而您试图用 C C::instances;
调用它。您可以通过调用可用的构造函数来绕过它:
C C::instances(0,0);
或者为 C
提供默认构造函数。
与
static std::vector<C> instances;
它编译是因为没有创建任何元素,并且 std::vector
有一个默认构造函数来初始化一个空 vector 。但是
C::instances.push_back(C());
不会编译。
关于c++ - C++中的继承单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11046201/