1
Good afternoon, you guys! I’m studying for a C++ test I’m doing this week, and I’m having a hard time passing an object as a constructor parameter. Could you explain to me the right way to do it?
I have the following code:
#include <iostream>
#include <string>
using namespace std;
class Data {
public:
Data(int dia, int mes, int ano) {
this->dia = dia;
this->mes = mes;
this->ano = ano;
};
void setData(int dia, int mes, int ano) {
this->dia = dia;
this->mes = mes;
this->ano = ano;
};
string getData() {
string d = to_string(this->dia);
string m = to_string(this->mes);
string a = to_string(this->ano);
return d + "/" + m + "/" + a;
}
private:
int dia, mes, ano;
};
class Pessoa {
public:
Pessoa(Data d) {
this->data = d;
};
private:
Data data;
};
int main()
{
Data data1(1, 2, 1995);
Data *data2 = new Data(3,4,1996);
cout << data1.getData() << endl;
cout << data2->getData() << endl;
//Pessoa p(data1);
//Pessoa *p2 = new Pessoa(data2);
return 0;
}
As possible see in the section below, I tried to create a constructor that would receive a Date and allocate it in the Data encapsulated field:
class Pessoa {
public:
Pessoa(Data d) {
this->data = d;
};
private:
Data data;
};
But when compiling, I have this problem:
||=== Build: Debug in Aprendizado1 (compiler: GNU GCC Compiler) ===|
D:\Lucas\DESENVOLVIMENTO\12 Semestre\Aprendizado1\main.cpp||In constructor 'Pessoa::Pessoa(Data)':|
D:\Lucas\DESENVOLVIMENTO\12 Semestre\Aprendizado1\main.cpp|33|error: no matching function for call to 'Data::Data()'|
D:\Lucas\DESENVOLVIMENTO\12 Semestre\Aprendizado1\main.cpp|8|note: candidate: Data::Data(int, int, int)|
D:\Lucas\DESENVOLVIMENTO\12 Semestre\Aprendizado1\main.cpp|8|note: candidate expects 3 arguments, 0 provided|
D:\Lucas\DESENVOLVIMENTO\12 Semestre\Aprendizado1\main.cpp|6|note: candidate: constexpr Data::Data(const Data&)|
D:\Lucas\DESENVOLVIMENTO\12 Semestre\Aprendizado1\main.cpp|6|note: candidate expects 1 argument, 0 provided|
D:\Lucas\DESENVOLVIMENTO\12 Semestre\Aprendizado1\main.cpp|6|note: candidate: constexpr Data::Data(Data&&)|
D:\Lucas\DESENVOLVIMENTO\12 Semestre\Aprendizado1\main.cpp|6|note: candidate expects 1 argument, 0 provided|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
If I add an empty constructor (no parameters), it works, but I don’t think it’s the right solution. How would it be the right one? Thank you!