copy constructor est assez spécial!!!
parce que "copy constructor" définit "pass-by-value"
#include <iostream>
class A
{
private:
int i;
public:
explicit A(): i(0) {};
explicit A(int _i): i(_i) {};
explicit A(A const & rhs)
{
std::cout << "appel copy constructor" << std::endl;
this->i = rhs.i;
};
int getA(void) const
{
return (this->i);
}
};
void test(A a)
{
std::cout << "dans le function A, i est " << a.getA() << std::endl;
}
int main(void)
{
A oa(5);
test(oa);
return (0);
}
dans ce code,
on a les eurres les suivantes:
main.cpp:34:7: error: no matching constructor for initialization of 'A'
test(oa);
^~
main.cpp:11:12: note: explicit constructor is not a candidate
explicit A(int _i): i(_i) {};
^
main.cpp:13:13: note: explicit constructor is not a candidate
explicit A(A const & rhs)
^
main.cpp:9:12: note: explicit constructor is not a candidate
explicit A(): i(0) {};
^
main.cpp:25:13: note: passing argument to parameter 'a' here
void test(A a)
^
1 error generated.
(base) ✘ hyungyoo 🌙 ~/t
pour quoi?
parce que l'on a "copy constructor avec explicit"!!!
mais, dans ce ca la, j'ai mis "explicit", donc cela complie pas!
pour resoudre ce probleme,
#include <iostream>
class A
{
private:
int i;
public:
explicit A(): i(0) {};
explicit A(int _i): i(_i) {};
// enlever "explicit"
A(A const & rhs)
{
std::cout << "appel copy constructor" << std::endl;
this->i = rhs.i;
};
int getA(void) const
{
return (this->i);
}
};
void test(A a)
{
std::cout << "dans le function A, i est " << a.getA() << std::endl;
}
int main(void)
{
A oa(5);
test(oa);
return (0);
}
---
appel copy constructor
dans le function A, i est 5
#include <iostream>
class A
{
private:
int i;
public:
explicit A(): i(0) {};
explicit A(int _i): i(_i) {};
explicit A(A const & rhs)
{
std::cout << "appel copy constructor" << std::endl;
this->i = rhs.i;
};
int getA(void) const
{
return (this->i);
}
};
// "Passe-by-reference-to-const"
void test(A const &a)
{
std::cout << "dans le function A, i est " << a.getA() << std::endl;
}
int main(void)
{
A oa(5);
test(oa);
return (0);
}
---
// appel copy constructor <-- pas d'appel "copy constructor"
dans le function A, i est 5