здесь мой оригинальный код класса, где я делаю копию с *this = src
, и результат отлично работает. Итак, вопрос, почему это работает с обычным class
, а не с template
? Плюс я представляю поведение с обычным классом, адрес остается прежним. И способ инициализации всех членов может быть сложным, если много членов переменных в классе? main.c
#include "Vec2.hpp"
#include <iostream>
int main() {
Vec2 a;
Vec2 b(21,42);
Vec2 c(a);
std::cout << a << std::endl;
std::cout << "c.get_x(): " << c.get_x() << std::endl;
std::cout << "c.get_y(): " << c.get_y() << std::endl;
std::cout << "b.get_x(): " << b.get_x() << std::endl;
std::cout << "b.get_y(): " << b.get_y() << std::endl;
std::cout << "a.get_x(): " << a.get_x() << std::endl;
std::cout << "a.get_y(): " << a.get_y() << std::endl;
a = b;
std::cout << "a.get_x(): " << a.get_x() << std::endl;
std::cout << "a.get_y(): " << a.get_y() << std::endl;
return 0;
}
Vec2.cpp
#ifndef VEC2_H
# define VEC2_H
#include <iostream>
class Vec2 {
public:
Vec2(); // canonical
Vec2(float const x, float const y);
Vec2(Vec2 const &); // canonical
~Vec2(); // canonical
Vec2 & operator=(Vec2 const & rhs); // canonical
static int get_instance();
float get_x() const ;
float get_y() const ;
private:
static int instance;
float x;
float y;
};
std::ostream & operator<< (std::ostream & out, Vec2 const & rhs);
#endif
vec2.hpp
#include "Vec2.hpp"
#include <iostream>
Vec2::Vec2() : x(0), y(0) {
std::cout << "Default constructor" << std::endl;
Vec2::instance++;
return;
}
Vec2::Vec2(float const x, float const y) : x(x), y(y) {
std::cout << "Parametric constructor" << std::endl;
Vec2::instance++;
return;
}
Vec2::Vec2(Vec2 const & src) {
*this = src;
std::cout << "Copy constructor" << std::endl;
Vec2::instance++;
return;
}
Vec2::~Vec2() {
std::cout << "Destructor" << std::endl;
Vec2::instance--;
return;
}
Vec2 & Vec2::operator=(Vec2 const & rhs) {
this->x = rhs.get_x();
this->y = rhs.get_y();
return *this;
}
int Vec2::get_instance(){
return Vec2::instance;
}
float Vec2::get_x() const {
return this->x;
}
float Vec2::get_y() const {
return this->y;
}
std::ostream & operator<< (std::ostream & out, Vec2 const & rhs) {
out << "[ " << rhs.get_x() << ", " << rhs.get_y() << " ]";
return out;
}
int Vec2::instance = 0;