因此,对于我的作业,我有两个不同的班级。一个是“客户”,另一个是“汉堡”类。我将这两种方法都实现了,可以在其中调用其中任何一个的对象,并通过随机生成来填充程序运行所需的数据。
需要执行的主要功能是“客户”类中的eat()函数。为了使其运行,需要向其中传递一个“ Burger”对象。在执行此操作之前,只需通过main将手动生成的“ Burger”对象传递给它。但是,我需要我的程序能够即时生成“ Burger”对象,最好是通过“ Customer”类中的eat()函数。是否可以通过其他类的函数创建类对象?
This is the eat() function that receives a burger object from main.
This is currently how I'm calling the burger object and passing it to the customer
这只是一个测试阶段,因此看起来不太漂亮。但是我希望可以通过在客户类中生成burger对象来避免这种情况。
答案 0 :(得分:0)
简短的回答:是的,只要已正确定义了您要创建的对象(向前声明是不够的)。考虑以下示例:
标题-
#include <iostream>
#include <string>
class A {
public:
A(std::string S = "");
std::string s;
void makeB(std::string S);
};
class B {
public:
B(std::string S = "");
std::string s;
void makeA(std::string S);
};
实施-
#include "classes.h"
A::A(std::string S) {
s = S;
}
void A::makeB(std::string S) {
B b(S);
std::cout << "B: "+b.s << std::endl;
}
B::B(std::string S) {
s = S;
}
void B::makeA(std::string S) {
A a(S);
std::cout << "A: "+a.s << std::endl;
a.makeB(S);
}
主要-
#include "classes.h"
int main() {
B b;
b.makeA("Hello world");
}
输出-
A: Hello world
B: Hello world
这适用于任何适当定义的类,包括将类A
中的类B
或类B
中的类A
制成。