여기서 x와 y의 값은 기본 클래스 생성자를 통해 설정하려고합니다.
그러나 코드는 그렇게 할 수 없습니다.
#include <iostream>
class Point2d {
public:
double x;
double y;
Point2d() : x(0), y(0) {
}
Point2d(double x, double y) : x(x), y(y) {
}
void Show() {
std::cout << "(" << x << "," << y << ")\n";
}
};
class Vector2d : public Point2d {
public:
Vector2d():Point2d(){
}
Vector2d(double x, double y) : Point2d(x,y) {
}
Vector2d(Vector2d const& vec) : Point2d(vec){
}
void Set(double x, double y) {
Point2d::Point2d(x, y);
}
};
int main() {
Vector2d v;
v.Set(20, -39);
v.Show(); // prints '(0,0)' instead of '(20,-39)'
}
내 목표는 기본 클래스 생성자를 재사용하고 할당 연산자를 가능한 한 많이 오버로드하는 것입니다.
코드가 컴파일되지 않을까 봐 걱정됩니다.
void Set(double x, double y)
{
Point2d::Point2d(x, y);
}
기본 클래스의 생성자는 멤버 함수가 아닌 하위 클래스 생성자의 멤버 이니셜 라이저 목록의 시작 부분에서 호출되어야합니다.
필요한 것은 아마도
class Point2d {
public:
double x;
double y;
Point2d() : x(0), y(0) {
}
Point2d(double x, double y) : x(x), y(y) {
}
void Show() {
std::cout << "(" << x << "," << y << ")\n";
}
Point2d& operator=(Point2d const& rhs)
{
this->x = rhs.x;
this->y = rhs.y;
}
};
class Vector2d : public Point2d {
public:
Vector2d():Point2d(){
}
Vector2d(double x, double y) : Point2d(x,y) {
}
Vector2d(Vector2d const& vec) : Point2d(vec){
}
/* also need to be overloaded in the subclass */
Vector2d& operator=(Vector2d const& rhs)
{
Point2d::operator=(rhs);
return *this;
}
void Set(double x, double y) {
*this = Vector2d(x, y);
}
};
int main() {
Vector2d v;
v.Set(20, -39);
v.Show();
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다