c与c++基本相同,他们也是兼容的,在c中可以调用C++函数,在c++中也可以调用C的函数
语法
绝对部分关键字for while switch if
c++与C的区别
- 标准输入输出
cout 输出流,代表显示器的一个流,把数据写入到这个流里面,就相当于写出到显示器上
<< 流的输入运算符,把数据输入到流里面
endl 一个对象,代表一个换行符
“\n” linux ; "\r\n" windows
cin 输入流,代表键盘的一个流,从cin中读数据,就相当于从键盘读数据
>> 从一个流里面取出数据 cin >> i;
- 头文件
如何使用c库自带的库函数
#include <stdio.h> c标准方式
#include <cstdio> c++标准方式,推荐
nm 用来查看程序中所有函数(见命令详解笔记)
D:\QQPCmgr\Desktop\C++\lesson1\lesson1\2\debug>nm test.o
00000000 b .bss
00000000 d .data
00000000 N .debug_abbrev
00000000 N .debug_aranges
00000000 N .debug_frame
00000000 N .debug_info
00000000 N .debug_line
00000000 N .debug_loc
00000000 t .text
00000000 T _myswap
在C语言的头文件中加入这个关键字,是为了让c++编译器明确的按照c的规范去调用这个头文件中声明的函数
extern
"C"
{
extern void myswap(int *a, int *b);
}
#ifndef TEST_H
#define TEST_H
#ifdef __cplusplus
extern "C"
{
#endif
__cplusplus
extern
void
myswap
(
int
*a
,
int
*b
);
#ifdef __cplusplus
}
#endif
#endif // TEST_H
int a; //定义
extern int a; //声明
- 命名空间:可以避免大型软件中函数命名的冲突
using namespace std;
namespace
baidu //定义命名空间baidu
{
int a = 20;
void test()
{
cout << a << endl;
}
}
namespace
google //定义命名空间google
{
int a = 10;
void test1()
{
cout << a << endl;
}
}
using
namespace
baidu
;
using
namespace
goole
;
如果没有引入命名空间的话,但是你又要用命名空间里面的变量或者函数,那么就要明确的指定用哪个命名空间的变量,函数
baidu::a; google::a;
其中
:: 叫做
域限制符
#include <iostream>
//using namespace std;
namespace baidu
{
int a = 10;
void test_baidu()
{
std::cout << a << std::endl;
}
}
namespace google
{
int a = 20;
void test_google()
{
std::cout << a << std::endl;
}
}
//using namespace baidu;
using namespace google;
int main()
{
int a = 30;
//test_baidu();
baidu :: test_baidu(); //a = 10
test_google(); //a = 20
std::cout << a << std::endl; //a = 30
std::cout << baidu::a << std::endl;
std::cout << google::a << std::endl;
return 0;
}
- 结构体与类的区别
什么是类: 在程序中用来描述一类事物的属性与动作。。
类里面可以包含成员变量与成员函数
用类定义一个变量,我们成为类的实例化。这个变量,我们叫做这个类的对象或者实例
作用域: 类声明部分和类的成员函数定义的部分
类内,类外
在类外,类的对象只能访问该类的public区的成员(成员变量和成员函数)
定义类的方法:
1.符合c语法 (结构体不是真正的类?)
struct
person //成员公有
{
//public:默认
char name[20];
int age;
int weight;
void short()
{
cout << "我是" << name << end;
}
};
2.c++定义方法
class
person //封装性,,其中的成员私有
{
public: //变成公有 ,private:私有默认
char name[20];
int age;
int weight;
void short()
{
cout << "我是" << name << end;
}
};
以及public private关键字
class person struct person
#include <iostream>
#include <cstring>
using namespace std;
#if 0
struct person
{
char name[20];
int age;
int weight;
void shout()
{
cout << "我是" << name << endl;
}
void init()
{
strcpy(name, "逍遥硖");
age = 20;
weight = 60;
}
};
#endif
class person
{
public:
char name[20];
int age;
int weight;
void shout()
{
cout << "我是" << name << endl;
}
void init()
{
strcpy(name, "原始人");
age = 20;
weight = 55;
}
private:
void test()
{
init();
}
};
int main()
{
//struct person p = {"逍遥硖", 20, 60}; // C
// struct person p;
person p;
p.init();
p.shout();
cout << p.name << endl;
cout << p.age << endl;
p.weight = 60;
cout << p.weight << endl;
// p.test(); //因为test是私有成员
return 0;
}
待完善。。。。。