类没有命名的成员
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;
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 助记符和指向成员语法的指针
- 用于访问容器<T>数据成员的正确 API
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 嵌套在类中时无法设置成员数据
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 将函数类成员映射到类本身内部
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 将公共但非静态的成员函数与ALGLIB集成
- 多成员Constexpr结构初始化
- 我们可以访问一个不存在的联盟的成员吗