【码农笔记】c++笔记(一)

1.指针

2.动态分配内存

int *p = new int; // 为变量请求内存
*p = 10; // 在分配的地址存储值

cout << *p << endl;

delete p; // 释放内存

忘记释放使用new关键字分配的内存将导致内存泄漏,因为内存将保持分配状态,直到程序关闭。可以使用 delete 运算符释放它所占用的内存

动态分配内存可以分配给数组

3.rand()函数

创建随机数,需要包含头文件

include<iostream>

#include<cstdlib>

using namespace std;

int main(){

cout<<rand()

}

rand() 函数只会返回一个伪随机数。这意味着每次运行代码时,都会生成相同的编号

4.srand() 函数用于生成真正的随机数(随机种子)。

srand() 函数允许指定一个种子(seed) 值作为其参数,用于rand() 函数的算法

int main () {

srand(30);

for (int x = 1; x <= 10; x++) {

cout << 1 + (rand() % 5) << endl;

}

}

更改种子(seed) 值会改变rand() 的返回值。但是,相同的参数将导致相同的输出。

在 C++ 中,生成真正随机数的方法是使用当前时间作为srand() 函数的种子值。

下面是一个例子,用time() 函数来获得系统时间的秒数,并随机种子给rand() 函数。在使用时,我们需要包含<ctime>头文件。

#include <iostream>

#include <cstdlib>

#include <ctime>

using namespace std;

int main () {

srand(time(0));

for (int x = 1; x <= 10; x++) {

cout << 1 + (rand() % 5) << endl;

}

}

time(0) 将返回当前秒数,提示srand() 函数每次程序运行时为rand() 函数设置一个不同的种子。每次我们运行程序时,使用这个种子值将会创建一个不同的输出。

5.能仅通过返回类型的不同来重载函数

6.将数组传递给函数

在 C++ 中,一个数组也可以作为参数传递给一个函数。

声明函数时,参数应该用方括号[] 来定义。

下面是一个例子:

void w3cArray(int arr[], int size) {

for(int x=0; x<size; x++) {

cout << arr[x];

}

}

7.函数传递参数的方式

传值调用

引用调用

向函数传递参数的引用调用方法,把引用的地址复制给形式参数。在函数内,该引用用于访问调用中要用到的实际参数。这意味着,修改形式参数会影响实际参数。

按引用传递值,参数引用被传递给函数,就像传递其他值给函数一样。

void swap(int *x) {

*x = 50;

}

int main() {

int var = 10;

swap(&var);

cout << var;

}

// 输出 50

使用操作符&的地址将变量直接传递给函数。

函数声明表示该函数将一个指针作为其参数(使用 * 运算符定义)。

结果,函数实际上已经改变了参数的值,通过指针访问它。

8.main()函数的类型如何定义?

9.类

class BankAccount {

};

用一个公开的方法创建一个类,并打印出 “Hi,W3cschool”。

class BankAccount {

public:

void sayHi() {

  cout << "Hi,W3cschool" << endl;

}

};

下一步是实例化 BankAccount 类的一个对象,就像定义一个类型的变量一样,区别
在于对象的类型是 BankAccount。

int main()

{

BankAccount test;

test.sayHi();

}

一个 private 成员不能从类外访问(对外不可见);只能从类内部进行访问。

#include <iostream>

#include <string>

using namespace std;

class myClass {

public:

void setName(string x) {
  name = x;
}

private:

string name

};

int main() {

myClass myObj;

myObj.setName("Loen");

return 0;

}

访问说明符

我们可以添加另一个公共方法来获取属性的值。

class myClass {

public:

void setName(string x) {
  name = x;
}
string getName() {
  return name;
}

private:

string name;

};

getName() 方法返回 私有属性 name 的值。

10.构造函数

11.类分布于文件