gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:08:02 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com