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

时间:2017-11-24 00:30:38

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

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

1 个答案:

答案 0 :(得分:0)

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

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