c++ - 为什么基类构造函数不设置值?

标签 c++ inheritance constructor

在这里,尝试通过基类构造函数设置 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();
}

关于c++ - 为什么基类构造函数不设置值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31978357/

相关文章:

c++ - 如何使用同一个类的成员函数删除当前类实例

c++ - 无法将指针向上转换为指针参数

java - 为可视类传递额外的参数?

c++ - 使用姐妹继承

c# - 继承类、泛型构造函数有问题

C++ - 构造函数被隐式删除,因为默认定义的格式不正确

javascript - 原型(prototype):应用与调用、新建与创建

c++读取数组结构问题

c++ - 如何在 Windows 上安装 GMP Mp? (C++)

c++ - 在 C++ 中获取 "yyyymmdd"日期字符串的最简单方法(允许提升)