首页 > 解决方案 > 类没有名为的成员

问题描述

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

每当我编译时,都会出现错误"class 'ShapeTwoD' has no member name getx() and gety()"。我尝试使用 setx 和 sety 直接设置 x 和 y 值,但它仍然返回相同的错误。

类 ShapeTwoD 是只有变量“名称”和“容器”的基类。如果有人能指导我正确的方向,将不胜感激。

主文件

#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; 
}

平方.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;
}

标签: c++

解决方案


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


推荐阅读