不被调用的c++默认构造函数[duplicate]

时间:2022-11-04 18:56:39

This question already has an answer here:

这个问题已经有了答案:

I am very new to c++ so forgive me if I have overlooked something simple. I have a class Circle:

我是c++新手,所以如果我忽略了一些简单的东西,请原谅我。我有一个班级圈:

class Circle: public Shape{
protected:
     //string name;
     Point focus;
     float radius;
private:

public:
    virtual void calculateArea();
    virtual void calculatePerimeter();
    Circle();
    Circle(Point p, float r);

};

};

I have two constructors, one of which is the default which I have overloaded:

我有两个构造函数,其中一个是我重载的默认构造函数:

Circle::Circle()
{
    Point p(1,1);
    focus = p;
    radius = 10;
    name = "Circle";
    calculatePerimeter();
    calculateArea();
    cout<<"default circle"<<endl;
}
Circle::Circle(Point p, float r)
{
    focus = p;
    radius = r;
    name = "Circle";
    calculatePerimeter();
    calculateArea();
}

In my main I try to create two circles one using the each constructor, however the Circle being created with Circle() never gets created. I cannot for the life of me figure out why? There are no error messages or anything.

在我的主要工作中,我尝试使用每个构造函数创建两个圆圈,但是,用Circle()创建的圆永远不会被创建。我怎么也搞不懂为什么?没有错误消息或任何东西。

int main{
    Circle circle(a, 3.3);
    Circle c2();
}

2 个解决方案

#1


22  

 Circle c2();

Does not create an object, it declares a function by name c2 which takes no argument and returns a Circle object. If you want to create a object just use:

它不创建对象,而是以名称c2声明一个函数,该函数不接受参数并返回一个Circle对象。如果你想要创建一个对象,只需使用:

Circle c2;

#2


6  

This here is not an instantiation, but a function declaration:

这里不是实例化,而是函数声明:

// parameter-less function c2, returns a Circle.
Circle c2();

You need

你需要

Circle c2;

or

Circle c2{};  // requires c++11

#1


22  

 Circle c2();

Does not create an object, it declares a function by name c2 which takes no argument and returns a Circle object. If you want to create a object just use:

它不创建对象,而是以名称c2声明一个函数,该函数不接受参数并返回一个Circle对象。如果你想要创建一个对象,只需使用:

Circle c2;

#2


6  

This here is not an instantiation, but a function declaration:

这里不是实例化,而是函数声明:

// parameter-less function c2, returns a Circle.
Circle c2();

You need

你需要

Circle c2;

or

Circle c2{};  // requires c++11