本文主要探讨c++类相关知识。
类
对象大小和成员变量有关(同struct大小)
初始化列表初始化参数的顺序为类中参数定义顺序
初始化列表应用:
const常量成员只能初始化不能赋值
引用类型在定义时初始化且不能重新赋值
无默认构造函数的类类型(类属性包含其他类,子类初始化父类成员)
普通成员方法产生this指针
const成员方法产生const this指针
static成员方法不产生this指针
只读成员方法实现为const方法
demo1:
对象大小和成员变量有关(同struct大小)
初始化列表初始化参数的顺序为类中参数定义顺序
结构图:
示例代码:
run.sh
#!/bin/bash
if [ -f ./Makefile ]
then
make clean
fi
cmake .
make
echo "---------------------------------"
./pro
CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 3.28) #最低版本要求
SET(CMAKE_CXX_COMPILER "g++-11") #设置g++编译器
PROJECT(CLASS) #设置工程名
MESSAGE(STATUS "CPP test") #打印消息
ADD_EXECUTABLE(pro test.cpp) #生成可执行文件
clean.sh
rm -rf CMakeCache.txt CMakeFiles Makefile cmake_install.cmake *.o pro
test.cpp
#include <iostream>
using namespace std;
class Test
{
public:
Test(){};
Test(int m):a(b),b(m){};
~Test(){};
void print_msg() const;
private:
int a;
int b;
};
//只读成员方法实现为const方法
void Test::print_msg() const
{
cout << "a: " << this->a << endl;
cout << "b: " << this->b << endl;
}
int main()
{
//对象或类大小和成员变量有关(同struct大小)
cout << "sizeof(Test):" << sizeof(Test) << endl;
Test s;
cout << "sizeof(s):" << sizeof(s) << endl;
//初始化列表初始化参数的顺序为类中参数定义顺序
Test t(1);
t.print_msg();
return 0;
}
结果示例:
demo2:
初始化列表应用:
结构图:
示例代码:
run.sh
#!/bin/bash
if [ -f ./Makefile ]
then
make clean
fi
cmake .
make
echo "---------------------------------"
./pro
CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 3.28) #最低版本要求
SET(CMAKE_CXX_COMPILER "g++-11") #设置g++编译器
PROJECT(CLASS) #设置工程名
MESSAGE(STATUS "CPP test") #打印消息
ADD_EXECUTABLE(pro test.cpp) #生成可执行文件
clean.sh
rm -rf CMakeCache.txt CMakeFiles Makefile cmake_install.cmake *.o pro
test.cpp
#include <iostream>
using namespace std;
class Des
{
public:
Des(){};
Des(string d):description(d){};
~Des(){};
string print_des() const
{
return this->description;
}
private:
string description;
};
class Test
{
public:
Test() = delete;
~Test(){};
Test(int num,int data,string d):
num(num),
data(data),
des(d){};
void print_Test() const
{
cout << "num: " << this->num << endl;
cout << "data: " << this->data << endl;
cout << "description: " << this->des.print_des() << endl;
}
private:
const int num;
int &data;
Des des;
};
int main()
{
/*
* 初始化列表应用:
* const常量成员只能初始化不能赋值
* 引用类型在定义时初始化且不能重新赋值
* 无默认构造函数的类类型(类包含其他类)
*/
Test t1(1,2,"hello word");
t1.print_Test();
return 0;
}
结果示例: