c++ - 嵌套类变量调用

标签 c++ class nested

我想从这个开始: enter image description here

为此: enter image description here

我该怎么做?子类 square 和 rectangle 的函数如何知道使用父类 shape 的变量?

我如何从 main 设置长度和宽度?

#include <iostream>
#include <cmath>
using namespace std;

class SHAPES
{
      public:
      class SQUARE
      {
            int perimeter(int length, int width)
            {
                return 4*length;
            }
            int area(int length, int width)
            {
                return length*length;
            }
      };
      public:
      class RECTANGLE
      {
            int perimeter(int length, int width)
            {
                return 2*length + 2*width;
            }
            int area(int length, int width)
            {
            return length*width;
            }
      };

};

最佳答案

我推荐其他(更好?!)格式:

class Shape
{
protected:
    int length,width;
public: 
    Shape(int l, int w): length(l), width(w){}
    int primeter() const
    {
        return (length + width) * 2;
    }
    int area() const
    {
        return length * width;
    }
};

class Rectangle : public Shape
{
public
    Rectangle(int l, int w) : Shape(l,w){}
};

class Square : public Shape
{
public:
    Square(int l): Shape(l,l){}
};


int main()
{
    Rectangle r(5,4);
    Square s(6);

    r.area();
    s.area();
}

或者使用interface with virtual function .

关于c++ - 嵌套类变量调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15053708/

相关文章:

c++ - 了解 STL 中的迭代器

一个文件中的 Swift 类

Java:如何通过存储在变量中的名称访问类的字段?

c# - 与单例模式设计中使用的相同类型的类属性

mysql - SQL 嵌套带计数的子查询

Python:将列表元组的嵌套列表转换为字典?

java - 最小化图中的桥数

c++ - 如何编写 C 或 C++ 程序来充当内存和 CPU 周期填充器?

c++ - 获取进程用户名c++

hibernate - 如何使用jpa查询嵌套对象