美文网首页
c++primer 13.14-13.21

c++primer 13.14-13.21

作者: 青吟乐 | 来源:发表于2019-06-04 11:18 被阅读0次

13.14
因为这里使用的是合成拷贝构造函数,不会使用默认构造函数,所以三个值完全一样
13.15
会改变,因为使用拷贝构造函数会生成新的序列号,而且因为f方法的参数为非引用,所以会在调用f的时候会先使用使用拷贝构造函数构造一个副本,再进行输出,所以输出的三个值不同于abc各自的序号
13.16
会改变,因为使用拷贝构造函数会生成新的序列号,但是f方法参数为引用,所以输出的三个值不一样,但是与abc对应的序号是一样的
13.17
第14题

#include<iostream>
class numbered{

public:

    numbered(){
        std::cout<<"默认构造函数"<<std::endl;
        mysn=num++;
    }
    //静态变量
    static int  num;
    int mysn;

};
int numbered::num = 10;
void f(numbered s){
        std::cout<<s.mysn<<std::endl;
    }

int main()
{
    numbered a,b=a,c=a;
    f(a);
    f(b);
    f(c);
    return 0;
}

第15题

#include<iostream>
class numbered{

public:

    numbered(){
        std::cout<<"默认构造函数"<<std::endl;
        mysn=num++;
    }
    numbered(const numbered &a){
        std::cout<<"拷贝构造函数"<<std::endl;
        mysn=a.num++;
    }

    //静态变量
    static int  num;
    int mysn;

};
int numbered::num = 10;
void f(numbered s){
        std::cout<<s.mysn<<std::endl;
    }

int main()
{
    numbered a,b=a,c=a;
    f(a);
    f(b);
    f(c);
    return 0;
}


第16题

#include<iostream>
class numbered{

public:

    numbered(){
        std::cout<<"默认构造函数"<<std::endl;
        mysn=num++;
    }
    numbered(const numbered &a){
        std::cout<<"拷贝构造函数"<<std::endl;
        mysn=a.num++;
    }

    //静态变量
    static int  num;
    int mysn;

};
int numbered::num = 10;
void f(const numbered &s){
        std::cout<<s.mysn<<std::endl;
    }

int main()
{
    numbered a,b=a,c=a;
    f(a);
    f(b);
    f(c);
    return 0;
}


13.18

#include <iostream>
#include<string>
using std::string;
class Employee{
public :
    static int sta_num;
    Employee(){
        std::cout<<"默认构造函数"<<std::endl;
        num = sta_num++;
    }
    Employee(string &str){
        num = sta_num++;
        name = str;
    }
    Employee(const Employee& a){
        num = sta_num++;
        name = a.name;
    }
    Employee& operator=(const Employee &){
        return *this;
    }
~Employee() = default;
private :
    int num;
    string name;
};
int Employee::sta_num = 10;
int main()
{
    return 0;
}

13.19
需要,员工序号唯一,不能直接拷贝。
代码看上题
13.20
拷贝时:TextQuery和QueryResult类没有拷贝构造函数,只有合成的拷贝构造函数,因此,这两个类的成员都会被拷贝
赋值时销毁时也类似
13.21
不需要,因为TextQuery和QueryResult类功能较为单一,不需要拆分对某一个成员的单独处理(类似于每个对象都需要有单独的编号),所以合成拷贝构造函数即可

相关文章

网友评论

      本文标题:c++primer 13.14-13.21

      本文链接:https://www.haomeiwen.com/subject/onqlxctx.html