c++考试总结(二)

函数引用参数:如果我们在声明或定义函数的时候将函数的形参指定为引用,则在调用该函数时会将实参直接传递给形参,而不是将实参的拷贝传递给形参。如此一来,如果在函数体中修改了该参数,则实参的值也会被修改。这跟函数的普通传值调用还是有区别的。

#include<iostream>
using namespace std;

void swap(int &a, int &b);

int main()
{
    int num1 = 10;
    int num2 = 20;
    cout<<num1<<" "<<num2<<endl;
    swap(num1, num2);
    cout<<num1<<" "<<num2<<endl;
    return 0;
}

void swap(int &a, int &b)
{
    int temp = a;
    a = b;
    b = temp;
}

运行结果:

10 20
20 10

在类内部声明函数,在类外部定义函数:

class student
{
char name[20]; //姓名
int id_num; //学号
int age; //年龄
char sex; //性别
void set_age(int a);
int get_age()const;
};
//在类外部定义set_age函数
void student::set_age(int a)
{
age = a;
}
//在类外部定义get_age函数
int student::get_age()const
{
return age;
}

构造函数举例:

#include<iostream>
using namespace std;

class book
{
public:
    book(){}
    book(char* a, double p);
    void setprice(double a);
    double getprice();
    void settitle(char* a);
    char * gettitle();
    void display();
private:
    double price;
    char * title;
};

book::book(char* a, double p)
{
    title = a;
    price = p;
}

void book::display()
{
    cout<<"The price of "<<title<<" is $"<<price<<endl;
}

void book::setprice(double a)
{
    price = a;
}

double book::getprice()
{
    return price;
}

void book::settitle(char* a)
{
    title = a;
}

char * book::gettitle()
{
    return title;
}

int main()
{
    book Alice;
    Alice.settitle("Alice in Wonderland");
    Alice.setprice(29.9);
    Alice.display();
    book Harry("Harry Potter", 49.9);
    Harry.display();
    return 0;
}

C++参数初始化表

class book
{
public:
    book(){}
    book(char* a, double p);
    void setprice(double a);
    double getprice();
    void settitle(char* a);
    char * gettitle();
    void display();
private:
    double price;
    char * title;
};

book::book(char *a, double p):title(a),price(p){}

在函数首部与函数体之间增添了一个冒并加上title(a),price(p)语句,这个语句的意思相当于函数体内部的 title = a; price = p; 语句。

初始化const成员变量的唯一方法只有利用参数初始化表。

class Array
{
public:
    Array(): length(0)
    {
        num = NULL;
    };
private:
    const int length;
    int * num;
};

C++拷贝构造函数:

book(book &b);
book(const book &b);

析构函数:析构函数就是用于回收创建对象时所消耗的各种资源
析构函数特征:
(1)无返回值
(2)没有参数,不能被重载,因此一个类也只能含有一个析构函数
(3)函数名必须为“~类名”的形式,符号“~”与类名之间可以有空格

析构函数与构造函数调用顺序是反转过来的,先调用构造函数的后调用构造函数。我们通过下面的例子来加以说明。

#include<iostream>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值