我是新来的类和构造函数。该程序要求用户输入两个圆圈的名称。我定义了一个默认的构造函数来设置半径和名称的参数,并定义另一个构造函数以接受它们作为参数。我相信setName存在问题,它还告诉我构造函数已经定义。任何帮助表示赞赏!

#include <iostream>
#include <cstring>
#include <string>
using namespace std;

class Circle
{
private:
    double pi = 3.14;
    double radius;
    string *name;

public:

    Circle();

    Circle(double, string);

    Circle::Circle()
    {
        radius = 0.0;
        *name = nullptr;

    }

    Circle::Circle(double r, string n)
    {
        radius = r;
        *name = n;
    }

    ~Circle()
    {
        delete[] name;
    }

    void setRadius(double r)
    {
        if (r >= 0)
            radius = r;
        else
        {
            cout << "Invalid radius\n";
            exit(EXIT_FAILURE);
        }
    }

    double getRadius()
    {
        return radius;
    }

    double getArea()
    {
        return pi* radius * radius;
    }

    double getCircumference()
    {
        return 2 * pi * radius;
    }

    void setName(string n)
    {

        *name = n;
    }

    string getName()
    {
        return *name;
    }

};


int main()
{
    Circle circle1;
    Circle circle2;
    double circRad1;
    double circRad2;
    string name1;
    string name2;

    cout << "Enter the name for circle 1: ";
    getline(cin, name1);

    cout << "Enter the name for circle 2: ";
    getline(cin, name2);

    cout << "Enter the radius for cirle 1: ";
    cin >> circRad1;

    cout << "Enter the radius for cirle 2: ";
    cin >> circRad2;

    circle1.setRadius(circRad1);
    circle2.setRadius(circRad2);
    circle1.setName(name1);
    circle2.setName(name2);


    cout << "Circle 1 name: " << circle1.getName() << "\n";
    cout << "Circle 1 radius: " << circle1.getRadius() << "\n";
    cout << "Circle 1 area: " << circle1.getArea() << "\n";
    cout << "Circle 1 circumfrence: " << circle1.getCircumference() << "\n";
    cout << "\n";

    cout << "Circle 2 name: " << circle2.getName() << "\n";
    cout << "Circle 2 radius: " << circle2.getRadius() << "\n";
    cout << "Circle 2 area: " << circle2.getArea() << "\n";
    cout << "Circle 2 circumfrence: " << circle2.getCircumference() << "\n";

    return 0;
}

最佳答案

我看到的问题:

建设者

你有:

Circle();

Circle(double, string);

Circle::Circle()
{
    radius = 0.0;
    *name = nullptr;
}

Circle::Circle(double r, string n)
{
    radius = r;
    *name = n;
}


这是不正确的,因为前两行在您声明并定义语法时用错误的语法声明了构造函数。

删除前两行。

name的使用

目前尚不清楚为什么将string*用于name。使它成为对象,而不是指针。

string name;


然后,将构造函数更改为:

// Use the default constructor to initialize name
Circle() : radius(0.0) {}

Circle(double r, string n) : radius(r), name(n) {}


您可以完全删除析构函数。如果您坚持拥有一个,请将其更改为(不再需要delete name):

~Circle() {}


setName()更改为:

  void setName(string n)
  {
     name = n;
  }


getName()更改为:

  string getName() const
  {
     return name;
  }


PS:您尝试的代码向我表明,从一本好书中了解该语言的基础知识将使您受益。有关想法,请参见The Definitive C++ Book Guide and List

08-05 20:58
查看更多