我正在处理继承分配,并想首先测试我的基类及其 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;
}
Run Code Online (Sandbox Code Playgroud)
线与线之间存在核心区别
Ship LilCutie;
Run Code Online (Sandbox Code Playgroud)
和
LilCutie("Boat", 1993);
Run Code Online (Sandbox Code Playgroud)
首先是定义。定义描述并初始化变量。第二个是要执行的语句,由调用运算符 (operator()) 组成。
由于您没有为ship类型定义operator(),所以第二行是非法的。构造函数作为对象创建和初始化的一部分被调用。所以你应该写:
Ship LilCutie("Boat", 1993);
Run Code Online (Sandbox Code Playgroud)
或者
Ship LilCutie;
LilCutie = Ship("Boat", 1993);
Run Code Online (Sandbox Code Playgroud)
当然,在第二种情况下,第一行执行默认构造函数,第二行创建 Ship 类的一个新对象,并通过默认运算符执行其值的赋值(在字符串类字段的情况下可以正常工作,该字段定义了自己的operator=,就可以了)否则只有浅拷贝)。两行中的括号 () 是初始化语法。