c++ - 在标头和源中分离类会导致构建错误
问题描述
下面的代码片段是有意简化的,只是为了说明问题。我想在这里展示两个案例。第一个将所有代码放在一个文件中,如下所示。
#include <iostream>
class Base
{
protected:
double data;
public:
Base(double data);
};
Base::Base(double data = 10) : data{data}{}
class Derived : public Base
{
};
int main()
{
Derived d;
std::cout<<"End of program";
return 0;
}
到现在为止还挺好。一切都按预期工作。
但是,如果我将类拆分为它们的标题和源,如下所示。
基础.hpp
// Base.hpp
#pragma once
class Base
{
protected:
double data;
public:
Base(double data);
};
基数.cpp
// Base.cpp
#include "Base.hpp"
Base::Base(double data = 10) : data{data} {}
派生的.hpp
// Derived.hpp
#pragma once
#include "Base.hpp"
class Derived : public Base
{
};
派生的.cpp
// Derived.cpp
#include "Derived.hpp"
单独的.cpp
// separate.cpp
#include "Derived.hpp"
#include <iostream>
int main(){
Derived d;
std::cout<<"End of program";
return 0;
}
我遇到了很多构建错误,如下所示。
> Executing task: C/C++: g++.exe build active file <
Starting build...
"C:\mingw32\bin\g++.exe" -g *.cpp -o separate.exe -I F:\StackExchange\Programming\VSCode-Template/cpp
separate.cpp: In function 'int main()':
separate.cpp:5:13: error: use of deleted function 'Derived::Derived()'
Derived d;
^
In file included from separate.cpp:1:
Derived.hpp:4:7: note: 'Derived::Derived()' is implicitly deleted because the default definition would be ill-formed:
class Derived : public Base
^~~~~~~
Derived.hpp:4:7: error: no matching function for call to 'Base::Base()'
In file included from Derived.hpp:2,
from separate.cpp:1:
Base.hpp:8:5: note: candidate: 'Base::Base(double)'
Base(double data);
^~~~
Base.hpp:8:5: note: candidate expects 1 argument, 0 provided
Base.hpp:2:7: note: candidate: 'constexpr Base::Base(const Base&)'
class Base
^~~~
Base.hpp:2:7: note: candidate expects 1 argument, 0 provided
Base.hpp:2:7: note: candidate: 'constexpr Base::Base(Base&&)'
Base.hpp:2:7: note: candidate expects 1 argument, 0 provided
Build finished with error(s).
The terminal process terminated with exit code: -1.
问题
你能告诉我为什么会发生这个问题以及如何解决它吗?
解决方案
默认参数属于声明中(在标题中),而不是在定义中(在 .cpp 文件中)。
推荐阅读
- python - 如何在烧瓶中获取 ipv6 地址?
- python - 如何在jupyter笔记本上绘制空图而不是地址?
- php - 计算在 php 中的总工作时间
- amazon-redshift - 在 cloudformation 的输出中获取 Redshift 集群状态
- sql - SQL 检查两条记录之间的链接(CASE、WHEN、THEN)
- abap - 导出和导入 ABAP 类
- android - 媒体播放器文件未找到异常
- apache-nifi - 在 nifi 中更新对弹性搜索的获取请求
- html - 滑块旋转的透明图像中缺少 alt 属性
- php - 在与我的 PHP 相同的域中提供 nodejs 静态文件