C ++构造函数问题

时间:2013-07-30 01:08:07

标签: c++ class constructor return-type

我很长时间没有使用过c ++,而且我从来没有真正掌握过类 我决定通过制作一个小型几何应用来重新学习课程 这是square.h:

class Square{
public:
    float width;
    float height;
    float area;
    float perimeter;


    void Square(int,int);
    void Square();
    void ~Square();




};

这是square.cpp:

#include "square.h"

Square::Square (int w, int h){
    width = w;
    height = h;
    area = width * height;
    perimeter = (width*2)+(height*2);
}

Square::Square (){

}

Square::~Square (){

}

当我运行/构建程序时,它会显示error: return type specification for constructor invalid
我想这是说构造函数和析构函数应该是void之外的其他东西,但我认为我错了。

4 个答案:

答案 0 :(得分:3)

  

我想这是说构造函数和析构函数应该是void

以外的东西

是的,它应该是:

Square(int,int);
Square();
~Square();
  

我认为void表示函数没有返回任何内容?

是的,但这些不是功能。它们是构造函数和析构函数,它们不需要指定的返回类型。

答案 1 :(得分:0)

摆脱构造函数和析构函数中的void

Square(int,int);
Square();
~Square();

自从你学习以来的一个建议。如果您没有考虑将类变量暴露给子类,请将它们设为私有。

答案 2 :(得分:0)

在构造函数和析构函数中,根本不应该有返回类型,

class Square
{
public:
    float width;
    float height;
    float area;
    float perimeter;


    Square(int,int);
    Square();
    ~Square();

};

答案 3 :(得分:0)

Constructordestructor没有返回类型。它们是类的一种特殊功能,具有class的相同名称。

class Square{
public:
    float width;
    float height;
    float area;
    float perimeter;


    Square(int,int);
    Square();
    ~Square();




};