c++ - 使用继承类型调用基类函数

标签 c++ class function inheritance

我无法准确描述我想说的内容,但我想使用具有继承类型的基类函数。就像我想声明“Coord3D operator + (Coord3D);”在一个类中,但如果我将它与 Vector3D 操作数一起使用,我希望它返回 Vector3D 类型而不是 Coord3D。

在下面的这行代码中,我添加了两个 Vector3D,并得到一个 Coord3D 作为返回,正如 typeid().name() 函数告诉我的那样。如何重新组织我的类,以便在返回时获得 Vector3D?

#include <iostream>
#include <typeinfo>
using namespace std;

class Coord3D
{
public:
        float x, y, z;
        Coord3D (float = 0.0f, float = 0.0f, float = 0.0f);
        Coord3D operator + (Coord3D &);
};

Coord3D::Coord3D (float a, float b, float c)
{
        x = a;
        y = b;
        z = c;
}

Coord3D Coord3D::operator+ (Coord3D &param)
{
        Coord3D temp;
        temp.x = x + param.x;
        temp.y = y + param.y;
        temp.z = z + param.z;
        return temp;
}

class Vector3D: public Coord3D
{
public:
        Vector3D (float a = 0.0f, float b = 0.0f, float c = 0.0f)
        : Coord3D (a, b, c) {};
};

int main ()
{
        Vector3D a (3, 4, 5);
        Vector3D b (6, 7, 8);
        cout << typeid(a + b).name();
        return 0;
}

最佳答案

您想要的功能在基类中,但它返回一个基类(这是有道理的,因为 Coord3D 不知道 Vector3D 是什么)。如果您坚持不为 Vector3D 重写 operator+()(我认为如果您计划进行乘法等操作是公平的),您可以创建一个拷贝Vector3D 类中的构造函数,可以根据 Coord3D 结果构造一个 Vector3D

class Vector3D: public Coord3D
{
public:
        Vector3D (float a = 0.0f, float b = 0.0f, float c = 0.0f)
        : Coord3D (a, b, c) {};

        Vector3D (const Coord3D& param){ new ((Coord3D*)this) Coord3D(param); }
};

int main ()
{
        Vector3D a (3, 4, 5);
        Vector3D b (6, 7, 8);
        Vector3D c = a + b;
        cout << typeid(c).name();
        Sleep(1000);
        return 0;
}

关于c++ - 使用继承类型调用基类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17353175/

相关文章:

java - 使类泛化有什么意义?

c - 在 C 中将匿名结构作为参数传递

c++ - 编程风格 : when to add a variable?

c++ - virtual 关键字在函数声明中的位置

java - Kotlin 数学数字泛型类

C# 嵌套类/结构可见性

c++ - 将 unsigned char * 转换为 char *

c++ - 通过 Tcp 套接字发送文件大小

function - 在 ELF 中查找函数的起始偏移量

bash - Bash 中的 Shellshock 漏洞背后的行为是记录在案还是完全是故意的?