实现复制构造函数

Implementing Copy Constructor

我正在尝试为每个函数添加一个复制构造函数,以便 运行 主函数。我现在已经实现的 currenrtly 打印出 "b2.valuea = -858993460 b2.valueb = 10" 所以它正确读取 valueb 但显然 valuea 出了问题。有什么建议吗?

#include "stdafx.h"
#include <iostream>
using namespace std;


class A
{
  int valuea;

public:
int getValuea() const { return valuea; }
void setValuea(int x) { valuea = x; }

// copy constructor
A() {}
A(const A& original)
{
    valuea = original.valuea;
}


};

class B : public A
{

int valueb;

public:

int getValueb() const { return valueb; }
void setValueb(int x) { valueb = x; }

// copy constructor
B(){}
B(const B& original)
{
    valueb = original.valueb;
}

};

int main()
{

B b1;
b1.setValuea(5);
b1.setValueb(10);
B b2(b1);
cout << "b2.valuea = " << b2.getValuea() << "b2.valueb = " <<
    b2.getValueb() << endl;
}

您没有在派生的复制构造函数中调用 base-class 的复制构造函数。 改成这样:

B(const B& original) : A(original){
  valueb = original.valueb;
}

它会输出

b2.valuea = 5
b2.valueb = 10