C ++ study concluded (under)

5.1 inline function

inline void show(){
	cout << "Hello Wordl!" <<endl;
}
int main(){
	show();
}
  • Will show()copy the contents of the function to the main function to

5.2 returns a reference

int &sum(){
    int num = 1;
    int& rNum = num;
    return rNum;
}
int main(){
    int& ans = sum();
    cout << ans << endl;
    return 0;
}
  • Note: Do not return to a local object reference. When the function is finished, release the memory space allocated to a local object. In this case, a reference to a local object will point to the uncertainty of memory.

5.3 Function overloading

/* 重载决议1.不认识 &
 *         2.不认识 const
 */
// 重载: 函数名相同,参数不同;
void eating(int num);   //重载决议后的函数名字是:  eating_int
void eating(float num); //重载决议后的函数名字是:  eating_float

5.4 Function Templates

//定义虚拟类型
template <typename T>//只在下面一个函数有效
void Swap(T &a,T &b){
    T temp = a;
    a = b;
    b = temp;
}
int main()
{
    double num1 = 4.7,num2 = 5;
    Swap(num1,num2);
    cout << num1 <<"  "<< num2 << endl;
    return 0;
}

6. Object-Oriented

6.1 basis

class Student{
	private://私有属性
		int values;
	public://共有属性
		Student(){};    //构造函数
		~Student(){};   //析构函数
		void eat(); 	//函数的定义
};
//!!!一定要先写出关系来
Student::Student() : values(15) { //简单的赋值方法
	cout << "默认构造" << endl;
}
//类中函数方法的实现
Student::eat(){
	cout << "我是一个函数" << endl;	
}

The best definition .hppto file

6.2 heap and stack memory

int main(){
	Student stu;						//在栈内存中定义一个对象
	Student* ptr_stu = new Student();	//在堆内存中定义一个对象
	
	delete ptr_stu;		//!!!在堆内存定义的东西使用完结束后一定要释放堆内存
}

6.3 This pointer

class Student{
	private://私有属性
		int values;
	public://共有属性
		Student(){};    //构造函数
		~Student(){};   //析构函数
		void eat(); 	//函数的定义
};
Student::Student(){
	this->values = 5; //This指针只能在对象中用,是函数的第一个隐式参数
	this->eat();  	  //通过This指针使用对象的方法
}

6.4 operator overloading

class Integer{
    private:
        int m_value;
    public:
        //构造函数
        Integer() : m_value(0){}
        Integer(int value): m_value(value) {}
        //!!!重载运算符  实现两个对象相加
        const Integer operator+(const Integer other)const;
        //得到值
        int getValue() {return m_value;}
        //析构函数
        ~Integer(){};
};

//实现运算符的重载
const Integer Integer::operator+(const Integer other)const {
    Integer result(this->m_value + other.m_value);
    return result;
}
Published 31 original articles · won praise 13 · views 9888

Guess you like

Origin blog.csdn.net/qq_43497702/article/details/101636605