ShiLuoTianKongch
ShiLuoTianKongch
2017-06-07 10:44

求助:c++怎么为必要的类添加合适的拷贝构造函数、赋值操作符?

  • c++
  • class

//chair.h

 #ifndef SHAPE__H
#define SHAPE__H

#include <string>
#include <vector>
#include <iostream>

static int gid=0;
int getuid(){
    return ++gid;
}

class Seat{
private:
    int id;
public:
    Seat(){ id=getuid();std::cout<<"Seat() "<<id<<" called\n";}
    ~Seat(){ std::cout<<"~Seat() "<<id<<" called\n";}
    int getid() const {return id;}
};

class Leg{
private:
    int id;
public:
    Leg(){ id=getuid();std::cout<<"Leg() "<<id<<" called\n";}
    ~Leg(){ std::cout<<"~Leg() "<<id<<" called\n";} 
};

class Chair{
private:
    int id;
public:
    Chair(){ id=getuid();std::cout<<"Chair() "<<id<<" called\n";}
    ~Chair(){ std::cout<<"~Chair() "<<id<<" called\n";}
    void setSeat(Seat& s){ seat = s;}
    void setLeg(Leg& l){ legs.push_back(l);}
private:
    Seat seat;
    std::vector<Leg> legs;
};

class Swivel{
private:
    int id;
public:
    Swivel(){ id=getuid();std::cout<<"Swivel() "<<id<<" called\n";}
    ~Swivel(){ std::cout<<"~Swivel() "<<id<<" called\n";}   
};

class OfficeChair : public Chair{
private:
    int id;
public: 
    OfficeChair(){ id=getuid();std::cout<<"OfficeChair() "<<id<<" called\n";}
    ~OfficeChair(){ std::cout<<"~OfficeChair() "<<id<<"  called\n";}
    void setSwivel(Swivel& s) { swivel = s;}
private:
    Swivel swivel;
};

#endif

//chair.cpp

 #include "chair.h"
#include <iostream>
#include <string>
#include<iomanip>

using namespace std;

void test_1(){
    cout<<"test_1 begin\n";
    {
        Seat s;
        Leg L1;
        Leg L2;
        Leg L3;
        Leg L4;
        Swivel sw;
        OfficeChair oc;
        oc.setSeat(s);
        oc.setLeg(L1);
        oc.setLeg(L2);
        oc.setLeg(L3);
        oc.setLeg(L4);
        oc.setSwivel(sw);
    }
    cout<<"test_1 end\n";
}
int main(){
    test_1();
}

测试输出:
/*
test_1 modified begin
Seat() 1 called
Leg() 2 called
Leg() 3 called
Leg() 4 called
Leg() 5 called
Swivel() 6 called
Seat() 7 called
Chair() 8 called
Swivel() 9 called
OfficeChair() 10 called
Seat() copyed 11 1 called
Leg() copyed 12 2 called
Leg() copyed 13 12 called
Leg() copyed 14 3 called
~Leg() 12 called
Leg() copyed 15 13 called
Leg() copyed 16 14 called
Leg() copyed 17 4 called
~Leg() 13 called
~Leg() 14 called
Leg() copyed 18 15 called
Leg() copyed 19 16 called
Leg() copyed 20 17 called
Leg() copyed 21 5 called
~Leg() 15 called
~Leg() 16 called
~Leg() 17 called
Swivel() copyed 22 6 called
~OfficeChair() 10 called
~Swivel() 22 called
~Chair() 8 called
~Leg() 18 called
~Leg() 19 called
~Leg() 20 called
~Leg() 21 called
~Seat() 11 called
~Swivel() 6 called
~Leg() 5 called
~Leg() 4 called
~Leg() 3 called
~Leg() 2 called
~Seat() 1 called
test_1 end
*/

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答