C++构造函数问题

C++ constructor problems

本文关键字:问题 构造函数 C++      更新时间:2023-10-16

我已经很久没有使用c++了,我从来没有真正很好地掌握过类
我决定通过制作一个小型几何应用程序来重新学习课程
这是正方形。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以外的东西,但我认为我错了。

我想这是说构造函数和析构函数应该是void 之外的东西

是的,应该是:

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

我认为void意味着函数不返回任何内容?

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

在构造函数和析构函数中去掉void
Square(int,int);
Square();
~Square();

还有一个建议,因为你正在学习。如果您不想将类变量公开给子类,请将它们设为私有变量。

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

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

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

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

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

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


};