Проблема с конструктором по умолчанию
Пишу код на плюсах. Есть 2 класса, связанных отношением наследования. В конструктор класса CThree заносится новые значения для полей класса CTwo и новое значение для поля CThree. Но, при выводе значений на экран, для полей класса CTwo выводятся значения, присваиваемые конструктором по умолчанию из CTwo. Что с этим делать?
//Main
#include <ostream>
#include <iostream>
#include <String.h>
#include "CTwo.h"
#include "COne.h"
#include "CThree.h"
using namespace std;
int main()
{
setlocale(LC_ALL, "Russian");
CThree A;
A.PrintF(); // <----- Выводит конструктор по умолчанию класса CTwo
}
//CTHREE.h
#ifndef CTHREE_H
#define CTHREE_H
#include "CTwo.h"
#include <iostream>
#include <string>
using namespace std;
class CThree:public CTwo
{
protected:
int a;
public:
CThree();
CThree(string S, string SOne, double D,int A);
virtual ~CThree();
CThree(const CThree& arg);
void PrintF();
int Get();
};
#endif
//CTHREE.CPP
#include "CThree.h"
#include "CTwo.h"
#include <string>
#include <iostream>
using namespace std;
CThree::CThree()
{
CTwo("TEST1","TEST2",0);
a = 0;
}
CThree::CThree(string S, string SOne, double D,int A)
{
CTwo(S, SOne, D);
a = A;
}
CThree::~CThree()
{
}
CThree::CThree(const CThree& arg)
{
a = arg.a;
}
void CThree::PrintF()
{
CTwo::Print();
cout << "a = " << a << endl;
}
int CThree::Get()
{
return a;
}
//CTWO.h
#ifndef CTWO_H
#define CTWO_H
#include <iostream>
#include <string>
#include "COne.h"
using namespace std;
class COne;
class CTwo
{
protected:
string s;
COne obj;
public:
CTwo();
CTwo(string S, string SOne, double d);
CTwo(const CTwo& arg);
virtual ~CTwo();
void Print();
const string& getS();
const COne& getObj();
CTwo& operator=(const CTwo& arg);
friend class COne;
friend class CThree;
};
#endif
//CTWO.CPP
#include "CTwo.h"
#include "COne.h"
#include <ostream>
using namespace std;
CTwo::CTwo()
{
s = "Конструктор по умолчанию С2";
obj = COne("Конструктор по умолчанию С1", 128);
}
CTwo::CTwo(string S, string SOne, double D)
{
s = S;
obj = COne(SOne, D);
}
CTwo::~CTwo()
{
s.clear();
}
CTwo::CTwo(const CTwo& arg)
{
this->obj = COne(arg.obj);
this->s = arg.s;
}
CTwo& CTwo::operator=(const CTwo& arg)
{
CTwo temp(arg);
std::swap(obj, temp.obj);
std::swap(s, temp.s);
return *this;
}
void CTwo::Print()
{
cout << "CTwo S = " << s << endl;;
obj.Print();
}
const string& CTwo::getS()
{
return s;
}
const COne& CTwo::getObj()
{
return obj;
}
Ответы (1 шт):
Автор решения: Harry
→ Ссылка
Конструкторы должны иметь примерно такой вид:
CThree::CThree():CTwo("TEST1","TEST2",0)
{
a = 0;
}
CThree::CThree(string S, string SOne, double D,int A):CTwo(S, SOne, D)
{
a = A;
}
А по-хорошему, даже
CThree::CThree():CTwo("TEST1","TEST2",0),a(0){}
CThree::CThree(string S, string SOne, double D,int A):CTwo(S, SOne, D):a(A){}