简体   繁体   中英

c++ Type does not provide a call operator error?

I'm working on an inheritance assignment and wanted to firstly test out my base class with its setters, getters, and constructors, but I'm already hitting a wall. What's wrong with my constructor? I would normally just use a no argument constructor and use the setters and getters to build the object, but we're specifically told to use both types of constructors. Can someone help me out?

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;

class Ship
{
public:
    Ship(); 
    Ship(string theName, int theYear);
    string getName();
    void setName(string);
    int getYear();
    void setYear(int);
    void printInfo();

    private:
    string name;
    int yearBuilt;     
};

Ship:: Ship()
{
   name = "";
   yearBuilt = 0;
}

Ship:: Ship(string theName, int theYear)
{
    name = theName;
    yearBuilt = theYear;
}

string Ship::getName()
{
    return name;
}

void Ship::setName(string newName)
{
    name = newName;
}

int Ship:: getYear()
{
    return yearBuilt;
}

void Ship:: setYear(int newYear)
{
    yearBuilt = newYear;
}

void Ship:: printInfo()
{
    cout << "Name: " << name << endl;
    cout << "Year built: " << yearBuilt << endl;
}

int main()
{
    Ship lilCutie;
    lilCutie("Boat", 1993);
    lilCutie.printInfo();

    return 0;
}

There is core difference between line

Ship LilCutie;

and

LilCutie("Boat", 1993);

First is a definition. Definition describes and initializes a variable. Second is a statement to execute, consisting of call operator (operator()).

As you didn't defined operator() for type ship, the second line is illegal. Constructors are called as part of creation and initialization of object. So you should write either:

Ship LilCutie("Boat", 1993);

or

Ship LilCutie;

LilCutie = Ship("Boat", 1993);

Of course, in second case first line executes default constructor, second line creates a new object of Ship class and performs assignment of its value by default operator (will work fine in case of string class field, which had own operator= defined, would do only a shallow copy otherwise). Parenthesis () in both lines are syntax for initialization.

You can call constructor with no parameter, then use setters to set value to it:

Ship lilCutie;
lilCutie.setName("Boat");
lilCutie.setYear(1993);

Also you can do that by calling constructor with parameters:

Ship lilCutie("Boat", 1993);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM