问题描述
我不愿意提出这个问题,但是我在HOURS上一直在尝试这个问题,我无法弄清楚。我是C ++的新手,无法弄清楚为什么sprintf_s不会在结尾处放任何东西(或就此而言,两者都不放)。基本上,除了弹出窗口外,在Visual Studio 2019中什么也没有发生。我知道这是一个简单的解决方案,但是我很想找出答案。另外,我是否需要主电源,或者没有主电源应该可以工作吗?好吧,我的构造函数看起来还好吗?我在其下弯曲着绿色,不确定如何解决它,或者不确定是否可以忽略它。我感谢我能获得的所有帮助!谢谢!
//#include "stdafx.h" - commented out as I think this version of VS does
//this automatically (I looked under precompiled headers and it was listed as "precompiled Header File"
//and it wouldn't work unless I commented it out
#include <iostream>
using namespace std;
// Base Entree class
class Entree
{
protected:
char _entree[10];
public:
const char* getEntree()
{
return _entree;
}
};
// Base Side class
class Side
{
protected:
char _side[10];
public:
char* getSide()
{
return _side;
}
};
class Drink
{
protected:
char _drink[10];
public:
Drink()
{
cout << "\n Fill cup with soda" << endl;
strcpy_s(_drink,"soda");
}
char* getDrink()
{
return _drink;
}
};
// ADDED CODE:
class ComboMeal
{
private:
Entree* entree;
Side* side;
Drink* drink;
char _bag[100];
public:
ComboMeal(const char* type)
{
sprintf_s(_bag,"/n %s meal combo: ",type);
}
void setEntree(Entree * e)
{
entree = e;
}
void setSide(Side * s)
{
side = s;
}
void setDrink(Drink * d)
{
drink = d;
}
const char* openMealBag()
{
sprintf_s(_bag,"%s,%s,%s",_bag,entree->getEntree(),side->getSide(),drink->getDrink());
return _bag;
}
};
int main()
{
}
解决方法
正如注释中所述,在C ++中执行的代码是main
函数中的代码。创建对应类的对象时将调用构造函数,因此您至少应具有以下内容:
int main(){
ComboMeal combo("my type one");
return 0;
}
一个更完整的示例是:
int main(){
ComboMeal combo("my type one");
combo.setEntree(new Entree);
combo.setSide(new Side);
combo.setDrink(new Drink);
cout << combo.openMealBag() << endl;
return 0;
}
(当然,这会打印垃圾,因为未设置新对象中的值)