c++ 小知识
1.指定字符串编码格式
std::string param = u8"我是一个小白兔";//指定utf8编码格式
2.正则表达式匹配字符串,并得到新字符串
string str = "{\"data\":[{\"featureId\":\"苏州市_区边界.1\",\"编号\":\"1\",\"objectid_1\":\"1\",\"objectid\":\"1\",\"名称\":\"吴中区\",\"编码\":\"\",\"gxsj\":\"\"}]}";
std::smatch result;
std::regex pattern("\"[^\"]+\":\"[^\"]+\"");
std::string Modify("[{");
std::string::const_iterator iter_begin = str.cbegin();
std::string::const_iterator iter_end = str.cend();
while (std::regex_search(iter_begin, iter_end, result, pattern))
{
std::string temp_str(result[0].str());
iter_begin = result[0].second; //更新迭代器位置
Modify = Modify + temp_str + ",";
}
Modify = Modify.substr(0, Modify.length() - 1); //去除多余的一个逗号
Modify = Modify + "}]";
Modify.insert(0, "{\"type\":\"postgis\",\"content\":");
Modify.append("}");
cout << Modify << endl;
链接: 菜鸟教程–正则相关知识.
3. fstream一次性读取整个文件
std::string ll = u8"测试文本-----加换行符\n";
std::fstream writeFile;
writeFile.open("F:\\c++learning\\资源\\test.txt", std::ios::in| std::ios::out);
std::stringstream buffer;
buffer << writeFile.rdbuf(); //读取整个文件
std::string contents(buffer.str());
writeFile.write(contents.c_str(), contents.size());//再次进行写入
4. ofstream读写文件
#include <filesystem>
std::experimental::filesystem::path filePath = std::experimental::filesystem::u8path("D:\\test\\circle_file.txt");
std::ofstream ofs(filePath, std::ios::app);
char str[1000];
sprintf(str, "x轴.x=%f x轴.y=%f, x轴.z=%f \n", pos.x, pos.y, pos.z);
ofs.write(str, strlen(str));
char str1[1000];
sprintf(str1, "up.x=%f up.y=%f, up.z=%f \n切线.x=%f 切线.y=%f, 切线.z=%f \n -----------------------------------\n", up.x, up.y, up.z, tangent.x, tangent.y, tangent.z);
ofs.write(str1, strlen(str1));
链接: 菜鸟教程–文件和流.
5. 关于基类和子类有重名函数,基类函数有无virtual的情况
-
子类和父类函数名相同,base::fun()函数有virtual关键字,则由实际绑定的类型决定调用哪个函数。
-
子类和父类函数名相同,但base::fun()函数没有virtual关键字,则由对象的类型决定调用哪个函数。
#include <iostream>
#include <string>
#include<sstream>
class base1
{
public:
virtual void test_base1()
{
std::cout << "调用基类函数test_base1\n" << std::endl;
}
};
class base2
{
public:
void test_base2()
{
std::cout << "调用基类函数test_base2\n" << std::endl;
}
};
class child1:public base1
{
public:
virtual void test_base1() override
{
std::cout << "调用子类函数test_child1\n" << std::endl;
}
};
class child2 :public base2
{
public:
void test_base2()
{
std::cout << "调用子类函数test_child2\n" << std::endl;
}
};
int main()
{
child1* test_child1 = new child1;
child2* test_child2 = new child2;;
base1* test_base1 = test_child1;
base2* test_base2 = test_child2;
test_child1->test_base1(); //子类调用函数
test_child2->test_base2();
test_base1->test_base1(); //父类指针调用函数
test_base2->test_base2();
test_base1->base1::test_base1(); //子类强制调用父类的函数
test_base2->base2::test_base2();
return 0;
}
输出结果:
调用子类函数test_child1
调用子类函数test_child2
调用子类函数test_child1
调用基类函数test_base2
调用基类函数test_base1
调用基类函数test_base2
6. 关键字override的作用
-
override一般和virtual连用
-
如果基类中有一个用 virtual 的虚函数,那么子类里面重写该函数的时候,应该在这个函数后面加 override
-
override会帮你检查是否基类中存在该虚函数,如果不存在,会在编译阶段报错,提醒你。
-
override这个关键词,为了代码规范,建议在子类的虚函数后面添加override。