C++基础

2021-02-09  本文已影响0人  来金德瑞

基础知识

发展历史

截屏2021-02-09 下午1.57.33.png

cin、cout

#include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
    int age;
    cin >> age;
    cout << "age is " << age << endl;
    return 0;
}

函数重载(Overload)

#include <iostream>
using namespace std;


// 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(int argc, const char * argv[]) {
    display();
    display(10);
    display(10l);
    display(10.1);
    return 0;
}

extern "C"

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


extern "C" void func2(int age) {
    cout << "func(int age)" << age << endl;
}


extern "C" {
    void func3(){
        cout << "func()" << endl;
    }

    void func4(int age) {
        cout << "func(int age)" << age << endl;
    }
}
extern "C" void func();
extern "C" void func2(int a);

extern "C" {
    void func3();
    void func4(int a);
}

void func() {
    cout << "func()" << endl;
}

void func2(int a) {
    cout << "func(int a) " << a << endl;
}
// sum.h

#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
// sum.c

#include "sum.h"

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

int minus(int a, int b) {
    return a - b;
}
// main.cpp
#include <iostream>
#include "sum.h"
using namespace std;
int main(int argc, const char * argv[]) {
    cout << sum(10, 20) << endl;
    return 0;
}

默认参数

#include <iostream>
using namespace std;

int age = 33;

void test() {
    cout <<  "test()" << endl;
}

void display(int a = 11, int b = 22, int c = age, void (*func)() = test) {
    cout << "a is " << a << endl;
    cout << "b is " << b << endl;
    cout << "c is " << c << endl;
    func();
}

int main(int argc, const char * argv[]) {
    display();
    return 0;
}
#include <iostream>
using namespace std;

void display(int a, int b = 20) {
    cout << "a is" << a << endl;
}

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

int main(int argc, const char * argv[]) {
    // Call to 'display' is ambiguous
    display(10);
    return 0;
}

内联函数

#include <iostream>
using namespace std;

inline int sum(int a, int b);

int main() {
    sum(10, 20);

    getchar();
    return 0;
}

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

内联函数与宏

#pragma once

上一篇下一篇

猜你喜欢

热点阅读