C++学习笔记3
发布人:shili8
发布时间:2025-01-26 03:12
阅读次数:0
**C++学习笔记3**
---
###1. 类和对象####1.1 类的定义在 C++ 中,类是用来描述一个事物或概念的模板。类可以包含数据成员(变量)和函数成员(方法)。下面是一个简单的例子:
cppclass Person {
public:
string name;
int age;
void sayHello() {
cout << "Hello, my name is " << name << " and I'm " << age << " years old." << endl;
}
};
####1.2 对象的创建类可以用来创建对象。下面是一个例子:
cppint main() {
Person person;
// 初始化数据成员 person.name = "John";
person.age =30;
// 调用方法 person.sayHello();
return0;
}
####1.3 类的访问控制在 C++ 中,类可以使用访问控制符来控制对其成员的访问。下面是一个例子:
cppclass Person {
public:
string name;
private:
int age;
};
在这个例子中,`name` 是公有的,而 `age` 是私有的。这意味着外部代码不能直接访问 `age`。
####1.4 类的继承类可以通过继承来扩展另一个类的功能。下面是一个例子:
cppclass Animal {
public:
void eat() {
cout << "Eating..." << endl;
}
};
class Dog : public Animal {
public:
void bark() {
cout << "Barking..." << endl;
}
};
在这个例子中,`Dog` 继承了 `Animal` 的功能,并添加了自己的功能。
###2. 构造函数和析构函数####2.1 构造函数构造函数是用来初始化对象的特殊成员函数。下面是一个例子:
cppclass Person {
public:
string name;
int age;
Person(string n, int a) {
name = n;
age = a;
}
};
####2.2 析构函数析构函数是用来释放对象所占用的资源的特殊成员函数。下面是一个例子:
cppclass Person {
public:
string name;
int age;
~Person() {
cout << "Person object destroyed." << endl;
}
};
###3. 运算符重载运算符重载是指在类中重新定义内置类型的运算符。下面是一个例子:
cppclass Complex {
public:
double real;
double imag;
Complex(double r, double i) : real(r), imag(i) {}
friend Complex operator+(const Complex& a, const Complex& b);
};
Complex operator+(const Complex& a, const Complex& b) {
return Complex(a.real + b.real, a.imag + b.imag);
}
int main() {
Complex c1(3.0,4.0);
Complex c2(5.0,6.0);
Complex result = c1 + c2;
cout << "Result: (" << result.real << ", " << result.imag << ")" << endl;
return0;
}
在这个例子中,`+` 运算符被重载来支持复数的加法。
###4. 模板模板是 C++ 中的一种高级特性,它允许函数或类根据参数类型进行编译。下面是一个例子:
cpptemplate <typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}
int main() {
int result1 = max(3,5);
double result2 = max(3.0,5.0);
cout << "Max of3 and5: " << result1 << endl;
cout << "Max of3.0 and5.0: " << result2 << endl;
return0;
}
在这个例子中,`max` 函数根据参数类型进行编译。
---
以上就是本篇文章的全部内容。希望通过这些例子和注释,你可以更好地理解 C++ 的类、对象、构造函数、析构函数、运算符重载和模板等概念。

