编写此代码的更有效方法是什么?

时间:2015-10-22 03:21:43

标签: c++ inheritance

所以,我是C ++的新手,我正在努力学习继承。我写了一个程序,只是打印出不同形状的周长,即正方形和三角形。不幸的是,我这样做的方式最终会产生一些重复的代码。这就是我的意思:

#include <iostream>

class Shape {
public:
  int sides;
  int sideLength;
};

class Square : public Shape {
public:
  int sides = 4;
  int sideLength = 6;
  void calculatePerimeter() {
    int perimeter = sideLength * sides;
    std::cout << "perimeter length: " << perimeter << std::endl;
  }
};

class Triangle : public Shape {
public:
  int sides = 3;
  int sideLength = 4;
  void calculatePerimeter() {
    int perimeter = sideLength * sides;
    std::cout << "perimeter length: " << perimeter << std::endl;
  }
};

int main() {
  Square s;
  std::cout << "number of sides a square has: " << s.sides << std::endl;

  Triangle t;
  std::cout << "number of sides a triangle has: " << t.sides << std::endl;

  s.calculatePerimeter();
  t.calculatePerimeter();
}

如您所见,calculatePerimeter函数正在Square和Triangle类中使用。将它放在Shape类中并调用它会导致输出为0.如何才能使其更有效率,因此我不必为每个形状类复制/粘贴它?

7 个答案:

答案 0 :(得分:3)

使用继承时,可以考虑基类中的常见行为和状态,并使派生类使用其特定功能扩展此状态和行为。

  1. 从Shape中删除sides和sideLength成员。相反,在类Shape中提供返回这些值的虚函数,并使派生类覆盖它们。

  2. 移动方法计算周长到类Shape,并使用getSides()和getSideLength()实现它

    #include <iostream>
    
    class Shape {
    public:
      virtual int getSides() = 0;
      virtual int getSideLength() = 0;
      void calculatePerimeter() {
        int perimeter = getSideLength() * getSides();
        std::cout << "perimeter length: " << perimeter << std::endl;
      }
    };
    
    class Square : public Shape {
    public:
      virtual int getSides() {
        return 4;
      }
    
      virtual int getSideLength() {
        return 6;
      }
    };
    
    class Triangle : public Shape {
    public:
      virtual int getSides() {
        return 3;
      }
    
      virtual int getSideLength() {
        return 4;
      }
    };
    
  3. 这就是所谓的模板方法设计模式(不要与C ++的模板函数概念混淆,后者是一种完全不相关的特定于该语言的概念)。

答案 1 :(得分:2)

您需要Shape的构造函数,并从派生的构造函数传递变量。然后,您可以将calculatePerimiter移动到父类中。

class Shape {
public:
  Shape(int n_sides, int side_length) : sides(n_sides), sideLength(side_length) {}

  void calculatePerimeter() {
    int perimeter = sideLength * sides;
    std::cout << "perimeter length: " << perimeter << std::endl;
  }

  int sides;
  int sideLength;
};

class Square : public Shape {
public:
  Square() : Shape(4,6) {}     
};

class Triangle : public Shape {
public:
  Triangle() : Shape(3, 4) {}
};

答案 2 :(得分:0)

此代码:

int sides = 3; int sideLength = 4;

正在使用本地范围视图创建新变量。如果不运行代码,我会想象如果你只是摆脱了&#39; int&#39;在两行前面应该解决你的问题。

编辑:当然将它们放入构造函数中。

编辑:好的,合并代码......

    class Triangle : public Shape {
public:

  Triangle ()
  {
    sides = 3;
    sideLength = 4;
  }

  void calculatePerimeter() {
    int perimeter = sideLength * sides;
    std::cout << "perimeter length: " << perimeter << std::endl;
  }
};

根据您想要了解的内容,其他答案是解决问题的更好方法。这很简单,只需将参数放入calcualatePerimeter()方法,但这当然不会测试您对范围内变量的理解,这似乎是您的绊脚石。

答案 3 :(得分:0)

您可以立即访问基类成员并初始化它们。

class Shape {
public:
  int sides;
  int sideLength;
  Shape(int m,int n)
  {
      sides =m;
     sideLength = n;
  }
};

class Square : public Shape {
public:
  Square(int j,int k);

  int calculatePerimeter() {
    int perimeter = sides * sideLength ;
    std::cout << "perimeter length: " << perimeter << std::endl;
    return perimeter;
  }
};

Square::Square(int j,int k):Shape(j,k)
{


}

答案 4 :(得分:0)

对于支持C ++ 11的编译器,这将是我的方法......

#include <iostream>
#include <string>
#include <vector>

using namespace std;

template<class Seq>
void purge(Seq& s) {
    for (auto x: s) {
        delete x;
        x = nullptr;
    }
}

class Shape {
public: 
    virtual void calculatePerimeter() = 0; // to avoid object slicing
    virtual ~Shape() {};
};

class Square : public Shape {
    int m_sides{0};
    int m_sideLength{0};
public: 
    Square() = delete; // suppress default constructor
    Square(int sides, int sideLength): m_sides(sides), m_sideLength(sideLength) {}
    ~Square() {}
    void calculatePerimeter() {
        int perimeter = m_sideLength * m_sides;
        cout << "Square perimeter length: " << perimeter << endl;
    }
};

class Triangle : public Shape {
    int m_sides{0};
    int m_sideLength{0};
public: 
    Triangle() = delete; // suppress default constructor
    Triangle(int sides, int sideLength): m_sides(sides), m_sideLength(sideLength) {}
    ~Triangle() {}
    void calculatePerimeter() {
        int perimeter = m_sideLength * m_sides;
        cout << "Triangle perimeter length: " << perimeter << endl;
    }
};

int main() {
    vector<Shape*> vec;

    vec.push_back(new Square(4, 7));
    vec.push_back(new Triangle(3, 13));

    for (auto x: vec) {
        x->calculatePerimeter();
    }

    // clean up
    purge(vec);

    system("pause");
    return 0;
}

答案 5 :(得分:0)

模板方式:

template <std::size_t SideCount, typename T>
class EquilateralPolygon
{
public:
    explicit EquilateralPolygon(T sideLength) : sideLength(sideLength) {}
    std::size_t GetSideCount() const { return SideCount; }
    T GetSideLength() const { return sideLength; }

    T calculatePerimeter() const { return SideCount * sideLength; }
private:
    T sideLength;
};

template <std::size_t SideCount, typename T>
void displayPerimeter(const EquilateralPolygon<SideCount, T>& p) {
    std::cout << "perimeter length: " << p.calculatePerimeter() << std::endl;
}

using EquilateralTriangle = EquilateralPolygon<3, std::size_t>;
using Square = EquilateralPolygon<4, std::size_t>;

用法:

int main() {
    Square s(5);
    std::cout << "number of sides a square has: " << s.GetSideCount() << std::endl;

    EquilateralTrianglet(5);
    std::cout << "number of sides a triangle has: " << t.GetSideCount() << std::endl;

    displayPerimeter(s);
    displayPerimeter(t);
}

Live Demo

答案 6 :(得分:-1)

这应该回答你的问题。另外,我建议将sidessideLength的值作为参数传递给函数调用,以启用泛型用法。

#include <iostream>

class Shape {
    protected void calculatePerimeter(int sides, int sideLength) {
    int perimeter = sideLength * sides;
    std::cout << "perimeter length: " << perimeter << std::endl;
  }
};

class Square : public Shape {
  int sides = 4;
  int sideLength = 6;
  public void calculatePerimeter()
  {
      Shape::calculatePerimeter(sides, sideLength);
  }
};

class Triangle : public Shape {
  int sides = 3;
  int sideLength = 4;
  public void calculatePerimeter()
  {
      Shape::calculatePerimeter(sides, sideLength);
  }
};

int main() {
  Square s;
  std::cout << "number of sides a square has: " << s.sides << std::endl;

  Triangle t;
  std::cout << "number of sides a triangle has: " << t.sides << std::endl;

  s.calculatePerimeter();
  t.calculatePerimeter();
}