我试图向每个添加一个副本构造函数以运行主要功能。我现在实现的内容现在会打印出“ 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;
}

最佳答案

您没有在派生的副本构造函数中调用基类的副本构造函数。
像这样更改它:

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


它会输出

b2.valuea = 5
b2.valueb = 10

10-08 09:30