【发布时间】:2016-03-02 21:10:39
【问题描述】:
我有一个不太明白的家庭作业问题。
向 Critter 类添加三个构造函数。每个构造函数都应该 还在屏幕上打印一条简单的信息消息,这样一个 可以查看何时以及调用了哪个构造函数。你应该可以 创建 Critter 类 1) 的实例而不提供任何 属性(应该将名称设置为“默认小动物”,高度 到 5 和其余到 0), 2) 只提供一个名称作为参数 (应该将高度设置为 5,其余设置为 0),以及 3)通过 提供姓名、饥饿、无聊和身高作为参数。你 也应该能够在没有的情况下创建 Critter 类的实例 指定高度。如果没有提供高度,则小动物有 默认高度为 10。编写一个测试程序,创建四个 通过使用这三个不同的构造函数的 Critter 实例 (两种方式的最后一种)。通过使用将他们的饥饿等级设置为 2 适当的方法和/或构造函数调用。小动物的属性 然后应该打印在屏幕上。
好的,所以首先我创建了一个类Critter,然后我在其中添加了 3 个构造函数,如第 1、2 和 3 点所述。然后我创建了一个对象或实例(它们是相同的东西,对吗?) .之后我创建了另一个对象并创建了另一个构造函数。问题是,我在最后 3 句话中迷失了:
编写一个测试程序,创建四个 通过使用这三个不同的构造函数的 Critter 实例 (两种方式的最后一种)。通过使用将他们的饥饿等级设置为 2 适当的方法和/或构造函数调用。小动物的属性 然后应该打印在屏幕上。
如何使用这三个不同的构造函数创建 4 个 Critter 实例?
这听起来像是一个愚蠢的问题,但我以前从未使用过课程。我是过程式编程的粉丝。
这是我的代码:
Critter.h
class Critter {
// The following data members are private
private:
std::string name;
int hunger, boredom;
double height;
public:
Critter();
Critter(std::string& newname);
Critter(std::string& newname, int newhunger, int newboredom, double newheight);
Critter(std::string& newname, int newhunger, int newboredom);
};
我在另一个文件中写道:
Critter.cpp
#include <iostream>
#include "Critter.h"
using namespace std;
Critter::Critter() {
name = "default critter";
height = 5.0;
hunger = 0;
boredom = 0;
cout << "First with no properties." << endl;
}
Critter::Critter(string& newname) {
name = newname;
height = 5.0;
hunger = 0;
boredom = 0;
cout << "Only name as a parameter." << endl;
}
Critter::Critter(string& newname, int newhunger, int newboredom, double newheight) {
name = newname;
height = newheight;
hunger = newhunger;
boredom = newboredom;
cout << "All as parameters." << endl;
}
Critter::Critter(string& newname, int newhunger, int newboredom) {
name = newname;
height = 10.0;
hunger = newhunger;
boredom = newboredom;
cout << "All as parameters." << endl;
}
和主文件:
#include <iostream>
#include "Critter.h"
using namespace std;
int main() {
Critter first_instance, second_instance;
string name;
int hunger, boredom;
double height;
return 0;
}
期待您的建议/答案。
谢谢
【问题讨论】:
-
示例:
Critter second_instance{"bob", 0, 0, 3.0};。这将使用构造函数Critter(string& newname, int newhunger, int newboredom, double newheight))创建一个实例 -
Critter(std::string& newname, int newhunger, int newboredom);不是请求的一部分 - 应该总共有 3 个构造函数(你写的其他三个) -
@M.M 这意味着我只需要创建一个对象并调用这些构造函数 4 次?谢谢
-
不,您需要创建 4 个对象。每个对象只能调用一次构造函数:“调用构造函数”是“创建对象”的同义词。
-
@M.M 非常感谢!
标签: c++ class oop object constructor