在一个静态库项目中,我有一个带声明但未实现的函数的头文件.
我有一个实现这些功能的.cpp文件.
然后,为了更好地理解链接器错误,我复制了cpp文件,所以我有一个完全重复的它也被编译.因此,两个文件都有标头中每个符号的双重实现.
它编译,当在另一个项目中使用时,它会链接.
这是静态库的最小示例:
api.hpp:
void printWhatever();
Run Code Online (Sandbox Code Playgroud)
errortest.cpp和duplicate.cpp是相同的:
#include "api.hpp"
#include <iostream>
void printWhatever(){
std::cout << "hi " << "\n";
}
Run Code Online (Sandbox Code Playgroud)
我将其编译为包含这两个源文件的静态库.我看到编译器为两个文件生成报告.
现在我在一个可执行文件中使用这个编译库,一个不同的项目:main.cpp:
#include <api.hpp>
int main(int argc, const char * argv[]) {
printWhatever();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它运行并打印"hi".
为什么函数没有多重定义?
任何人都可以解释我从这个简单的程序使用的输出std::map
.请注意,我插入p
到地图中,但还q
没有说它发现它们两者,但也说地图中只有1个元素!
#include <map>
#include <iostream>
struct screenPoint {
float x = 0, y = 0;
screenPoint(float x_, float y_): x{x_}, y{y_}{}
};
bool operator<(const screenPoint& left, const screenPoint& right){
return left.x<right.x&&left.y<right.y;
}
std::map<screenPoint, float> positions;
int main(int argc, const char * argv[]) {
auto p = screenPoint(1,2);
auto q = screenPoint(2,1);
positions.emplace(p,3);
auto f = positions.find(p);
auto g = positions.find(q);
if (f == positions.end()){
std::cout << "f not found";
} else {
std::cout << …
Run Code Online (Sandbox Code Playgroud) 我理解这个C++函数的作用,但我不明白为什么return
语句是这样编写的:
int intDivide(int num, int denom){
return assert(denom!=0), num/denom;
}
Run Code Online (Sandbox Code Playgroud)
这里只有一个声明,因为只有一个声明,;
但逗号让我困惑.为什么不写:
int intDivide(int num, int denom){
assert(denom!=0);
return num/denom;
}
Run Code Online (Sandbox Code Playgroud)
除了"优雅"之外,还有什么东西可以在第一个版本中获得?
无论如何,这个逗号究竟在做什么?它是否将单个陈述分为两部分,以致上述两个版本基本相同?
所有这些行都编译并运行,输出中没有打印:
std::string ss{6};
ss=7;
std::cout << "ss " << ss << "\n";
Run Code Online (Sandbox Code Playgroud)
我没有看到任何引用的构造函数std::string
,这表明它可以将整数强制转换为字符串,那么为什么编译器不会抱怨?
关于这两个函数是否具有相同逻辑的另一个问题似乎存在一些分歧:
bool operator<(const screenPoint& left, const screenPoint& right){
if (left.x < right.x) return true;
else return left.y < right.y;
}
bool operator<(const screenPoint& left, const screenPoint& right){
return left.x < right.x || left.y < right.y;
}
Run Code Online (Sandbox Code Playgroud)
我已经盯着这些看了很长一段时间,我看不出它们会有什么不同的表现.在两者中,如果left.x < right.x
,他们都返回true
.如果没有,那么他们都返回结果left.y < right.y
.对?
如果没有,有人可以详细说明.
另外,有人提出,其中第一个与词法排序的实现相同std::tie
,是真的吗?
有很多关于清理的问题和答案std::vector
,我想知道为什么,在我读过的所有内容中,没有人只是说:
existingVector = std::vector<whatever>();
这不是清除矢量的简单方法吗?
get <>在编译时强制执行,而不是at()或operator [].
现在我明白了at()
边界检查,但我想知道get
和之间的关键区别[]
- 页面operator[]
没有说明索引的运行时执行,所以上面的引用可能不太准确.
它们都采用size_type并返回一个元素引用,那么这个"在编译时强制执行"是get
什么意思呢?