简体   繁体   English

C++ 在继承的 class 中访问运算符 function

[英]C++ Accessing operator function in inherited class

I am currently writing an application where I use the Eigen-Library for complex 3D-Math.我目前正在编写一个应用程序,在其中使用 Eigen-Library 进行复杂的 3D-Math。 Because I needed distinct point and vector classes, my point3d-class looks like this:因为我需要不同的点和向量类,所以我的 point3d 类看起来像这样:

class point3d : public Eigen::Vector4d
{
public:
    point3d(){}
    point3d(double x, double y, double z) : Eigen::Vector4d(x, y, z, 1) {}
    void fromString(std::string input);
};

Now I want to create a member function of this class that allows me to parse lines of OBJ-files which look like this:现在我想创建这个 class 的成员 function ,它允许我解析 OBJ 文件的行,如下所示:

v 2.8 0.52 10.18

as such point.作为这样的点。 This is how I intend to design my parsing function这就是我打算如何设计我的解析 function

void point3d::fromString(std::string input)
{
    char* buf = strdup(input.c_str());
    if (strtok(buf, " ") == "v")
    {

        ;
        strtok(buf, " ");
        this-x = std::stod(strtok(buf, " "));
        this->y = std::stod(strtok(buf, " "));
        this->z = std::stod(strtok(buf, " "));  

    }
}

My problem is that Eigen does not allow me to access the data stored in Vector4d as this->x, this-y, this->z and so on.我的问题是,Eigen 不允许我以 this->x、this-y、this->z 等方式访问 Vector4d 中存储的数据。 Instead, you'd usually access it as Vector4d v;相反,您通常会以 Vector4d v 的形式访问它; v[0], v[1], v[2] etc. I think the way it does that is by using a v[0]、v[1]、v[2] 等。我认为这样做的方式是使用

double Eigen::Vector4d::operator[](unsigned int index){...}

function. function。

I don't know how exactly one would access that data in a derived class.我不知道如何在派生的 class 中访问该数据。 What do I have to do to access this data within that function so that I can write to the x, y, z values?我必须做什么才能访问 function 中的这些数据,以便我可以写入 x、y、z 值?

You can do你可以做

(*this)[0]

and so on in order to call the base class operator[] .依此类推,以调用基本 class operator[]

x , y , z aren't member variables of Eigen::Vector4d , but methods. x , y , z不是Eigen::Vector4d的成员变量,而是方法。 You can access them from your derived class using this->x() etc (or Vector4d::x() ).您可以使用this->x()等(或Vector4d::x() )从派生的 class 访问它们。 What also works is (*this)[0] or (*this)(0) .同样有效的是(*this)[0](*this)(0) If you need to access x() , y() , z() frequently in your class, you could write once:如果您需要在 class 中频繁访问x()y()z() ,则可以编写一次:

using Vector4d::x;
using Vector4d::y;
using Vector4d::z;

And afterwards access them using just x() , y() , z() .然后只使用x()y()z()访问它们。 However, this may cause some shadowing conflicts (if you name local variables the same way).但是,这可能会导致一些阴影冲突(如果您以相同的方式命名局部变量)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM