对于这段代码,我需要能够打印输出,但我不确定如何完成这项任务。我根本无法更改主函数,并且我正在寻找某个输出。预期的输出应该格式化为小部件名称、ID,然后是小部件的地址。我想我可以使用字符串作为输出,但我不确定如何实现它。
主.cpp是
#include <iostream>
#include <string>
#include "widget.h"
using namespace std;
int main()
{
//makes three widgets using the regular constructor
const Widget weather( WEATHER );
const Widget quote( QUOTE );
const Widget stock( STOCK );
cout << "weather widget 1: " << weather.getModelName() << endl;
cout << "quote widget 1: " << quote.getModelName() << endl;
cout << "stock widget 1: " << stock.getModelName() << endl;
//makes three widgets using the copy constructor
Widget weather2 = weather;
Widget quote2 = quote;
Widget stock2 = stock;
cout << "weather widget 2: " << weather2.getModelName() << endl;
cout << "quote widget 2: " << quote2.getModelName() << endl;
cout << "stock widget 2: " << stock2.getModelName() << endl;
cin.get();
return 0;
}
小部件.h是
#include <string>
using namespace std;
enum WidgetType
{
INVALID_TYPE = -1,
WEATHER,
QUOTE,
STOCK,
NUM_WIDGET_TYPES
};
const string WIDGET_NAMES[NUM_WIDGET_TYPES] = { "Weather2000",
"Of-The-Day",
"Ups-and-Downs"
};
class Widget
{
public:
Widget( WidgetType type );
//add copy constructor
Widget( const Widget& rhs );
string getModelName() const { return wModelName; };
WidgetType getType() {return wType;};
private:
WidgetType wType;
int wID;
string wModelName;
static int userID;
//add static data member
void generateModelName();
};
那么小工具.cpp就是
#include "iostream"
#include "widget.h"
int Widget::userID = 1;
Widget::Widget( WidgetType type )
{
wID = userID;
wType = type;
wModelName = wType;
userID++;
generateModelName();
}
Widget::Widget( const Widget& rhs )
{
wID = userID;
wType = rhs.wType;
wModelName = wType;
userID++;
generateModelName();
}
void Widget::generateModelName()
{
if (getType() == WEATHER)
{
wModelName = "Weather2000";
}
else if (getType() == QUOTE)
{
wModelName = "Of-The-Day";
}
else if (getType() == STOCK)
{
wModelName = "Ups-and-Downs";
}
}
最后,预期的结果是
weather widget 1: Weather2000 1 000000145FD3F628
quote widget 1: Of-The-Day 2 000000145FD3F678
stock widget 1: Ups-and-Downs 3 000000145FD3F6C8
weather widget 2: Weather2000 4 000000145FD3F718
quote widget 2: Of-The-Day 5 000000145FD3F768
stock widget 2: Ups-and-Downs 6 000000145FD3F7B8
您可以更改getModelName
以在std::ostringstream
的帮助下生成所需的输出。
旧实现:
string getModelName() const { return wModelName; };
新版本:
#include <sstream> // std::ostringstream
string getModelName() const {
std::ostringstream os;
os << 't' << wModelName << 't' << wID << " " << std::hex << this;
return os.str();
};
演示