派生类c ++中的upcasting变量

时间:2016-06-10 18:12:36

标签: c++ class derived-class upcasting

如何更改派生类中继承变量的类型? 我有以下课程:

class Position;
class StonePosition;

class Position {
public:
    Position() {}
};

class StonePosition : public Position {
    int count;
public:
    StonePosition(const int count) { this->count = count; }
    int getCount() { return this->count; }
    void setCount(int count) { this->count = count; }
    friend ostream& operator<<(ostream&, StonePosition);
};

class Board {
protected:
    Position* crrPos;
public:
    Board() { }
    Position* getCrrPos() { return crrPos; }
    void setCrrPos(Position* pos) { crrPos=pos; }
};

class StoneBoard : public Board {
public:
    StoneBoard(const int &count) { this->crrPos=new StonePosition(count); } //<----------------
    StonePosition* getCrrPos() { return (StonePosition*)crrPos; }
    void setCrrPos(StonePosition* pos) { crrPos=pos; }
};

问题用箭头标记的位置。我需要在StoneBoard类中将变量的类型从Position更改为StonePosition。我找到了一个可以用于upcasting的选项,但它只能在一个方法中工作,我需要更改整个类的变量。

问题解决了,看看我的答案。

2 个答案:

答案 0 :(得分:0)

变量&#34; crrPos&#34;不是类型的位置它是类型指向位置的指针,这很重要,因为指向位置的指针可以指向位置或类从位置派生而不会丢失任何东西。

如果您很好地设计课程并使用虚拟功能,通常可以避免完全升级。

#include <iostream>

class Base {
public:
    virtual void foo() { std::cout << "Base::foo()\n"; }
    virtual bool isDerived() const { return false; }
};

class Derived : public Base {
public:
    void foo() override { std::cout << "Derived::foo()\n"; }
    bool isDerived() const { return true; }
};

int main() {
    Base* crrPos = new Derived;
    crrPos->foo();
    bool isDerived = crrPos->isDerived();
    std::cout << isDerived << '\n';
    delete crrPos;
}

现场演示:http://ideone.com/UKcBaA

答案 1 :(得分:-2)

问题已经解决,我只使用投影((StonePosition *)位置*):

#include <iostream>
using namespace std;
class Position;
class StonePosition;

class Position {
public:
    Position() {}
};

class StonePosition : public Position {
    int count;
public:
    StonePosition(const int count) { this->count = count; }
    int getCount() { return this->count; }
    void setCount(int count) { this->count = count; }
    friend ostream& operator<<(ostream&, StonePosition);
};
template <typename TPos> class TBoard { 
protected:
    TPos* crrPos;
public:
    TBoard() { }
    TPos* getCrrPos() { return crrPos; }
    void setCrrPos(TPos* pos) { crrPos=pos; }
};
class Board {
protected:
    Position* crrPos;
public:
    Board() { }
    Position* getCrrPos() { return crrPos; }
    void setCrrPos(Position* pos) { crrPos=pos; }
};

class StoneBoard : public Board {
public:
    StoneBoard(const int &count) { this->crrPos=new StonePosition(count); } 
    Position* getCrrPos() { return crrPos; }
    void setCrrPos(Position* pos) { crrPos=pos; }
};

int main(){
    StoneBoard s(7);
    cout<<((StonePosition*)s.getCrrPos())->getCount();//<----right here
    system("pause");
    return 0;
}

它工作得很好:)。