c ++ Type不提供调用操作符错误?

时间:2017-01-25 06:14:00

标签: c++ constructor

我正在进行继承任务,并希望首先使用其setter,getter和构造函数测试我的基类,但我已经碰壁了。 我的构造函数有什么问题?我通常只使用一个无参数构造函数并使用setter和getter来构建对象,但我们特别要求使用这两种类型的构造函数。有人可以帮助我吗?

#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;
}

2 个答案:

答案 0 :(得分:2)

行之间存在核心差异

Ship LilCutie;

LilCutie("Boat", 1993);

首先是一个定义。定义描述并初始化变量。第二个是要执行的语句,由调用运算符(operator())组成。

由于您没有为类型船定义operator(),因此第二行是非法的。构造函数被称为对象的创建和初始化的一部分。所以你应该写:

Ship LilCutie("Boat", 1993);

Ship LilCutie;

LilCutie = Ship("Boat", 1993);

当然,在第二种情况下,第一行执行默认构造函数,第二行创建Ship类的新对象,并通过默认运算符执行其值的赋值(在字符串类字段的情况下将正常工作,其具有自己的运算符=已定义,否则只会做一个浅的副本)。两行中的括号()是初始化的语法。

答案 1 :(得分:1)

您可以调用不带参数的构造函数,然后使用setter为其设置值:

Ship lilCutie("Boat", 1993);

你也可以通过调用带参数的构造函数来做到这一点:

validFrom