繁体   English   中英

是否可以在同一类中重载()运算符作为取消引用和=运算符作为赋值?

[英]Is it possible to overload both the () operator as a dereference and the = operator as assignment in same class?

我正在开发一个程序,该程序具有指向Null值或派生子对象的对象指针网格。 我希望能够在此网格上将值设置为其派生子代的地址,这样我就可以“将”一个子代“放置”在网格上并通过其在内存中的位置访问该子代。

这是网格的界面外观。

class Grid{

public:
    virtual int get(g_type) const;

public:

    parent* operator() (int,int);

    Grid() : _amtCol(10),_amtRow(10)
    {construct();}

    ~Grid() {deconstruct();}

private:
    int _amtCol;
    int _amtRow;
    parent* **_grid;

private:
    parent ***meddle(access);
    void meddle(access, parent***);
    virtual void construct();
    virtual void deconstruct();
};

这是()重载的样子。

parent* Grid::operator() (int i,int j){

    if(i < get(r_QTY) && j < get(c_QTY)){

        return this->meddle(key)[i+1][j+1];

    }else{return NULL;}
}

我想要做的是在程序的其余部分中将此称为:

Grid b;
Child c;
Child c2;

b(1,1) = &c;
b(1,4) = &c2;

b(1,1)->foo(); //calls the first Childs foo()
b(1,4)->foo(); //calls the second Childs foo()

我的其余课程都是在继承和结构方面创建并起作用的。

有什么方法可以链接重载或类似的东西吗?

我以为也许我需要解决父母和孩子班上的作业超负荷问题,但他们似乎工作得很好。

///////////////////////////////////////////////////// ///

顺便说一句,我确实实现了这一点:

void Grid::operator() (int i,int j,parent &cpy){
    if(i < get(r_QTY) && j < get(c_QTY)){
        this->meddle(key)[i+1][j+1] = &cpy;
    }
}

确实允许使用此功能。

有我的论文! 谢谢!

///////////////////////////快速补充:因此,也许我不必知道这在道德上和道德上是否公正。 我有一种方法来实现有效的功能。 我想我确实知道,使用库中已有的东西比我自己创建的东西更可取,但是如果您使用std :: vector例如它是可行的,则意味着有可能。 我想知道如何做到这一点以及它在语言语法中的位置。

不确定确切的问题是什么,但是您可以执行以下操作:

struct parent
{
    virtual ~parent() = default;
    virtual void foo() = 0;
};

struct Child : parent
{
    Child(int n) : n(n) {}
    void foo() override { std::cout << n << std::endl;}
    int n;
};

class Grid{
public:
    Grid() : col(10), row(10), grid(col * row, nullptr) {}

    parent* operator() (std::size_t x, std::size_t y) const {
        if (col <= x || row <= y) { throw std::runtime_error("Invalid arguments"); }
        return grid[y * col + x];
    }

    parent*& operator() (std::size_t x, std::size_t y) {
        if (col <= x || row <= y) { throw std::runtime_error("Invalid arguments"); }
        return grid[y * col + x];
    }

private:
    int col;
    int row;
    std::vector<parent*> grid;
};

然后您有:

Grid b;
Child c(1);
Child c2(2);

b(1,1) = &c;
b(1,4) = &c2;

b(1,1)->foo(); //calls the first Childs foo()
b(1,4)->foo(); //calls the second Childs foo()

演示版

暂无
暂无

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

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