C++ 类和对象基本认识和创建
对象赋值语句:
对象1 = 对象2
注意的地方:
对象的类型必须相同。
两个对象之间的赋值,只是数据成员的赋值,而不对成员函数赋值。不同对象的成员函数占有不同的存储空间,而不同对象的成员函数是占用同一个函数代码段,无法对它们赋值。
当类中有 ++
指针 ++
时,需要进行深拷贝。
构造函数:
构造函数是一种特殊的成员函数,它主要用于为对象分配空间,进行初始化。
建立对象的两种形式:
形式1:
类名 对象[(实参表)]
例如:
Date date1(2016, 10, 14);
通过点.符号访问。
形式二:
类名 *指针变量名 = new 类名[实参表];
例如:
Date *pdate = new Date(2016, 10, 14);
这类对象没有名字,成为无名对象,通过指针->访问。
成员初始化列表:
例如:
class Date {
public:
Date(int x, int y, int z);
...
private:
int year;
int month;
int day;
};
Date::Date(int x, int y, int z):year(x), month(y), day(z) {}
带默认参数的构造函数:
例如:
class Coord {
public:
Coord(int a = 0, int b = 0);
...
};
默认参数应该从右边开始向左排。
构造函数是可以重载。
拷贝构造函数:
类名::类名(const 类名 &对象名) {
拷贝构造函数的函数体
}
调用默认构造函数的形式:
带入法:
类名 对象2(对象1);
赋值法:
类名 对象2 = 对象1;
例子:
#include
using namespace std;
class Rectangle {
public:
Rectangle(int len, int wid);
Rectangle(const Rectangle &p);
void showRectangle();
private:
int length;
int width;
};
Rectangle::Rectangle(int len, int wid) : length(len), width(wid) {
cout << "原始构造函数..." << endl;
}
Rectangle::Rectangle(const Rectangle &p) : length(2 * p.length), width(2 * p.width) {
cout << "拷贝构造函数..." << endl;
}
void Rectangle::showRectangle() {
cout << length << " " << width << endl;
}
int main(int argc, const char *argv[]) {
Rectangle test(25, 50);
test.showRectangle();
Rectangle copyTest = test;
copyTest.showRectangle();
cin.get();
return 0;
}
运行:
原始构造函数...
25 50
拷贝构造函数...
50 100
调用拷贝函数的情况:
用类的对象去初始化另一个对象。
Rectangle p2 = p1; // 带入法
Rectangle p2(p1); // 赋值法
当函数的形参是类的对象。
fun1 (Rectangle p) { // 形参是对象 p
p.disp();
}
int main() {
Rectangle p1(10, 20);
fun1(p1); // 调用对象,初始化形参对象p
return 0;
}
当函数返回值是对象,函数执行完后返回调用者时。
Rectangle fun2() {
Rectangle p1(10, 30);
return p1;
}
int main() {
Rectangle p2;
p2 = fun2();
return 0;
}
深拷贝浅拷贝:
深拷贝,另外得分配空间。
例子:
#include
#include
#include
using namespace std;
class StringAB {
public:
StringAB(char *s) {
ptr = new char[strlen(s) + 1];
strcpy(ptr, s);
cout << "构造函数 --- " << ptr << endl;
}
~StringAB() {
cout << "析构函数 --- " << ptr << endl;
delete[]ptr;
}
void show() {
cout << ptr << endl;
}
StringAB &operator = (const StringAB &);
private:
char *ptr;
};
StringAB &StringAB::operator = (const StringAB &pp) {
if (this == &pp) {
return *this;
}
delete[]ptr;
ptr = new char[strlen(pp.ptr) + 1];
strcpy(ptr, pp.ptr);
return *this;
}
int main(int argc, const char *argv[]) {
StringAB book("book"), jeep("jeep");
book.show();
jeep.show();
book = jeep;
book.show();
return 0;
}
运行:
构造函数 --- book
构造函数 --- jeep
book
jeep
jeep
析构函数 --- jeep
析构函数 --- jeep
请按任意键继续. . .
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了