【问题标题】:String Variable Argument Lists in C++C++ 中的字符串变量参数列表
【发布时间】:2011-07-19 02:54:24
【问题描述】:

我正在尝试使用可变参数列表来使基于文本的 RPG 中的 NPC 轻松交谈。有这么多错误,我什至懒得发布它们——我猜我用错了,你不需要输出。 如果你这样做,我当然会发布它。

这是您需要的两个文件:

//Globals.h

#ifndef _GLOBALS_
#define _GLOBALS_

//global variables

#include "Library.h"
//prototypes
bool Poglathon();
void NPCTalk(string speaker,string text,...);

//functions
void NPCTalk(string speaker,string text,...){
    va_list list;
    va_start(list,text);
    while(true){
        string t = va_arg(list,string);
        if (t.compare("")==0)
            break;
        cout << speaker << ": "<< t << endl << endl;
        system("PAUSE");
    }
}

#endif

还有一个:

//Library.h

#ifndef _LIBRARY_H_
#define _LIBRARY_H_

#include <iostream>
using namespace std;

#include "Globals.h"
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cstdarg>

#endif

【问题讨论】:

  • 如果你想使用std::string,你必须包含&lt;string&gt;
  • 尝试将非 POD 类型(例如 std::string)传递给可变参数函数不是一个好主意。结果将是不可移植的,并且它导致的问题可能难以调试。
  • 您正在尝试使用 C++ 语言编写 C 代码。

标签: c++ string list arguments variadic-functions


【解决方案1】:

字符串向量怎么样?

#include <vector>
#include <string>

void NPCTalk(std::string const& speaker, std::vector<std::string> const& text)
{
    for (std::vector<std::string>::const_iterator it = text.begin();
                                                  it != text.end(); ++it)
    {
        std::cout << speaker << ": " << *it << std::endl;
    }
}

【讨论】:

  • 这是什么const&amp;?我会试试的。
  • 你会得到一个不可修改的对象引用。
  • @Pig Head:你不会复制整个向量,这可能会很慢,因为如果 NPC 喜欢说话,它可能会很大。引用的行为类似于指针,并且不会复制。
  • 好的 - 我收到错误“命名空间 'std' 没有成员 'vector'”。奇怪吗?
  • @Pig:你#include &lt;vector&gt;了吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-13
  • 1970-01-01
  • 2020-04-19
  • 1970-01-01
  • 2021-04-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多