C++-入门语法(一)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_42528266/article/details/102734023
C++ 的发展历史

在这里插入图片描述

语法须知
  • C++的源文件扩展名是:cpp(c plus plus的简称)
  • C++程序的入口是main函数(函数即方法,一个意思)
  • C++完全兼容C语言的语法,很久以前,C++叫做C with classes
cin与cout

C++中常使用cin、cout进行控制台的输入、输出

  • cin用的右移运算符>>,cout用的是左移运算符<<
  • endl是换行的意思
#include <iostream>
using namespace std;

// 在Java的世界里,先有类,再有方法(函数)
int main() {

	//cout << "Hello World!" << endl;

	/*cout << "Hello";
	cout << endl;
	cout << "World!";*/

	//cout << "Hello" << endl << "World!";

	/*int age;
	cin >> age;

	cout << "age is " << age << endl;*/

	// Shift + F5:退出程序
	// Ctrl + SHift + F5:重启程序
	// 以上快捷键只针对F5启动的程序

	int a = 10;
	int b = a >> 2;
	// 面向对象 + 运算符(操作符)重载

	// 等待键盘输入
	getchar();

	return 0;
}
函数重载(Overload)
  • 规则
    • 函数名相同
    • 参数个数不同、参数类型不同、参数顺序不同
  • 注意
    • 返回值类型与函数重载无关
    • 调用函数时,实参的隐式类型转换可能会产生二义性
  • 本质:采用了name mangling或者叫name decoration技术
    • C++编译器默认会对符号名(变量名、函数名等)进行改编、修饰,有些地方翻译为“命名倾轧”
    • 重载时会生成多个不同的函数名,不同编译器(MSVC、g++)有不同的生成规则
    • 通过IDA打开【VS_Release_禁止优化】可以看到
#include <iostream>
using namespace std;

/*
C语言不支持函数重载
*/

// g++
// msvc


// display_v
void display() {
	cout << "display() " << endl;
}

// display_i
void display(int a) {
	cout << "display(int a) " << a << endl;
}

// display_l
void display(long a) {
	cout << "display(long a) " << a << endl;
}

// display_d
void display(double a) {
	cout << "display(double a) " << a << endl;
}

// 逆向工程
int main() {
	display();
	display(10);
	display(10l);
	display(10.1);

	getchar();

	return 0;
}
extern “C”
  • 被extern "C"修饰的代码会按照C语言的方式去编译
  • 如果函数同时有声明和实现,要让函数声明被extern "C"修饰,函数实现可以不修饰
  • 由于C、C++编译规则的不同,在C、C++混合开发时,可能会经常出现以下操作
    • C++在调用C语言API时,需要使用extern "C"修饰C语言的函数声明
  • 有时也会在编写C语言代码中直接使用extern “C” ,这样就可以直接被C++调用
#include <iostream>

//extern "C" {
#include "sum.h"
//}

// C语言库

using namespace std;

//extern "C" void func() {
//	cout << "func()" << endl;
//}
//
//extern "C" void func(int a) {
//	cout << "func(int a) " << a << endl;
//}

//extern "C" {
//	void func() {
//		cout << "func()" << endl;
//	}
//
//	void func(int a) {
//		cout << "func(int a) " << a << endl;
//	}
//}

//extern "C" void func();
//extern "C" void func(int a);

//extern "C" {
//	void func();
//	void func(int a);
//}

int main() {
	/*func();
	func(10);*/

	cout << sum(10, 20) << endl;

	getchar();

	return 0;
}

//void func() {
//	cout << "func()" << endl;
//}
//
//void func(int a) {
//	cout << "func(int a) " << a << endl;
//}

#include "sum.h"

// _sum
int sum(int a, int b) {
	return a + b;
}

int minus(int a, int b) {
	return a - b;
}

#ifndef __SUM_H
#define __SUM_H

#ifdef __cplusplus
extern "C" {
#endif // __cplusplus

int sum(int a, int b);
int minus(int a, int b);

#ifdef __cplusplus
}
#endif // __cplusplus

#endif // !__SUM_H

猜你喜欢

转载自blog.csdn.net/weixin_42528266/article/details/102734023