构造函数
#include<iostream>
using namespace std;
class Person {
public:
int age;
Person() {
cout << "无参构造" << endl;
}
Person(int a) {
age = a;
cout << "有参构造" << endl;
}
//拷贝构造参数
Person(const Person &p) {
age = p.age;
cout << "拷贝构造" << endl;
}
~Person() {
cout << "析构函数" << endl;
}
};
int main1() {
// Person p1;//无参构造
// Person p2(10);//有参构造
// Person p3(p2);//拷贝构造
//cout << "p2的age=" << p2.age << endl;
//cout << "p3的age=" << p3.age << endl;
//调用默认构造函数时不加()
//2.显示法
Person p1;
Person p2 = Person(15);
Person p3 = Person(p2);
//注意事项,不要利用拷贝构造函数来初始化一个匿名对象, 编译器会认为是对象的声明
//Person(p3);
//3.隐式转换法
//Person p4 = 10; //
//Person p5 = p4;
return 0;
}
深拷贝与浅拷贝
#include<iostream>
using namespace std;
class Person {
public:
int m_age;
int* m_height;
Person() {
cout << "无参构造" << endl;
}
Person(int age, int height) {
m_age = age;
m_height = new int(height);
cout << "有参构造" << endl;
}
//省略此步即为浅拷贝,编译器默认的拷贝构造函数为浅拷贝,析构时会重复释放指针导致报错
//Person(const Person &p) {
// m_age = p.m_age;
// m_height = new int(*p.m_height);
// cout << "拷贝构造" << endl;
//}
~Person() {
if (m_height != NULL) {
delete(m_height);
m_height = NULL;
}
cout << "析构函数" << endl;
}
};
void testG() {
Person p1(15, 177);
Person p2(p1);
cout << "p1的age = " << p1.m_age << " p1的height = " << *p1.m_height<< endl;
cout << "p2的age = " << p2.m_age << " p2的height = " << *p2.m_height<< endl;
}
int main() {
testG();
return 0;
}
对象特性——初始化列表
#include<iostream>
using namespace std;
class Person {
public:
int m_a;
int m_b;
int m_c;
Person(int a, int b, int c) :m_a(a), m_b(b), m_c(c) {
}
};
void test() {
Person p(15, 25, 0);
cout << p.m_a << endl;
cout << p.m_b << endl;
cout << p.m_c << endl;
}
int main() {
test();
}
类对象作成员
#include<iostream>
using namespace std;
class Phone {
public:
string m_phoneName;
Phone(string phoneName) {
m_phoneName = phoneName;
cout << "构造phone" << endl;
}
~Phone() {
cout << "析构phone" << endl;
}
};
class Person {
public:
Phone m_p;
string m_name;
Person(string phoneName, string name) :m_p(phoneName), m_name(name)
{
cout << "构造person" << endl;
}
~Person() {
cout << "析构person" << endl;
}
};
void test() {
Person p("iPhone", "motherfucker");
cout << p.m_p.m_phoneName << endl;
cout << p.m_name << endl;
};
int main() {
test();
return 0;
}
//打印结果,注意先构造对象成员,析构时顺序相反
//构造phone
//构造person
//iPhone
//motherfucker
//析构person
//析构phone
静态成员——静态函数
#include<iostream>
using namespace std;
class Person {
public:
int m_b;
static void func() {
cout << "调用静态函数" << endl;
s_a = 100;
//m_b = 0;静态成员函数只能访问静态变量,不能访问成员变量
}
private:
static int s_a;
};
int Person::s_a = 0;
void test() {
Person p;
p.func();
Person::func;
}
int main() {
test();
return 0;
}
成员变量与成员函数分开存储
#include<iostream>
using namespace std;
//成员变量和成员函数分开存储
class Person {
int m_A;//非静态成员变量 属于类的对象上
static int m_b;//静态的成员变量与成员函数 不属于类的对象上
void func(){}//非静态 不属于类的对象上
};
void test01() {
Person p;
//空对象占用空间1个字节
//c++编译器给空对象分配一个字节空间,是为了区分空对象占用的位置
//每个空对象都有一个独一无二的内存地址
cout << "size of p = " << sizeof(p) << endl;
}
int main() {
test01();
}
|