【问题标题】:Is it possible to overload both the () operator as a dereference and the = operator as assignment in same class?是否可以将 () 运算符重载为取消引用,将 = 运算符重载为同一类中的赋值?
【发布时间】:2017-11-24 00:30:37
【问题描述】:

我正在开发一个程序,它有一个指向 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 例如它是可行的,这意味着它是可能的。我想知道这是如何实现的,以及它在语言语法中的位置。

【问题讨论】:

标签: c++ pointers inheritance operator-overloading operator-keyword


【解决方案1】:

不确定你的问题是什么,但你可以这样做:

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()

Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    • 2013-02-14
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多