c++ - 类没有名为的成员
问题描述
我是 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;
}
解决方案
这很正常...如果将 sq1 声明为 ShapeTwoD,则可以访问 ShapeTwoD 公共成员方法/属性。甚至它是用 Square 构造函数实例化的。将其转换为 Square,您可以使用 getx gety。或者将 getx/gety 声明为 ShapeTwoD 的方法。
推荐阅读
- assembly - 为什么输出 1 比它应该的大?(部件)
- html - 内联块元素高度和可滚动内容框在 Angular 应用程序中的行为与 html-page 不同
- android - Android WebView播放视频报错闪黑屏
- c# - 在c#中提取路径的一部分
- angular - 从cordova(android/ios)访问站点时.net核心会话状态不保持
- spring - Spring Boot 和 Spring Data with Cassandra:在数据库连接失败时继续
- c# - 是否可以使用实体框架从 C# 中的多个表中获取连接 SQL 查询的结果?
- sql - 更新用于 SQL 报告的表中的批量数据的最佳实践
- git - 在 git 中,我如何验证错误修复是否在 Release 分支和 master 中
- php - 连接并搜索数据库,然后将其显示到网页?