类没有命名的成员

Class has no member named

本文关键字:成员      更新时间:2023-10-16

我是c++的新手,正在尝试了解其面向对象设计。我开始了一个小项目来测试继承和多态性,但遇到了一个问题,无法弄清楚出了什么问题。

每当我编译时,都会出现错误"类'ShapeTwoD'没有成员名称getx((和gety(("。我尝试使用 setx 和 sety 直接设置 x 和 y 值,但它仍然返回相同的错误。

类 ShapeTwoD 是只有变量 'name' 和 'container' 的基类。如果有人能指导我正确的方向,将不胜感激。

主.cpp

#include <iostream>
#include <string>
#include "ShapeTwoD.h"
#include "Square.h"
using namespace std;
int main()
{
    cout<<endl;
    ShapeTwoD *shape2D[100];
    ShapeTwoD *sq1 = new Square("Square", true, 4, 6);
    cout << sq1->getName() <<endl;
    cout << sq1->getContainer() <<endl;
    //sq1->setx(4) <<endl;
    //sq1->sety(6) <<endl;
    cout << sq1->getx() <<endl;
    cout << sq1->gety() <<endl;
    cout<<endl;
    delete sq1; 
}

Square.h

#include <iostream>
#include <string>
#include "ShapeTwoD.h"
using namespace std;
class ShapeTwoD; //forward declare
class Square : public ShapeTwoD
{
public:
    int x;
    int y;
    //constructor
    Square(string name, bool container,int x, int y);
    int getx();
    int gety();
    void setx(int x);
    void sety(int y);
};

方形.cpp

#include <iostream>
#include <string>
#include "Square.h"
#include "ShapeTwoD.h"
Square::Square(string name, bool containsWarpSpace, int coordx, int coordy)
   :ShapeTwoD(name, containsWarpSpace)
{
    (*this).x = coordx;
    (*this).y = coordy;
}
int Square::getx()
{
    return (*this).x;
}

int Square::gety()
{
    return (*this).y;
}
void Square::setx(int value)
{
    (*this).x = value;
}
void Square::sety(int value)
{
    (*this).y = value;
}

很正常...如果将 sq1 声明为 ShapeTwoD,则可以访问 ShapeTwoD 公共成员方法/属性。甚至它也被与 Square 构造函数实例化。将其转换为 Square,您可以使用 getx gety。或者将getx/gety声明为ShapeTwoD的方法。

好吧,这是你应该期待的,因为它有 shape2D 类型,虽然用方形构造函数构造它不允许您访问派生的类成员,但它将允许您有一个安全的类型强制转换来使用它。 最简单的方法是:

cout << static_cast<Square*>(sq1)->getx() << endl;
cout << static_cast<Square*>(sq1)->gety() << endl;