C++ C++;传一串
这可能是个显而易见的问题 如果我有:C++ C++;传一串,c++,string,function,C++,String,Function,这可能是个显而易见的问题 如果我有: void print(string input) { cout << input << endl; } 它抱怨我传递的是char*,而不是std::string。有没有办法在通话中打字?而不是: string send = "Yo!"; print(send); 谢谢。最明显的方法是这样调用函数 print(string("Yo!")); 您需要从中创建一个(临时的)std::string对象。嗯,std::string是一
void print(string input)
{
cout << input << endl;
}
它抱怨我传递的是char*,而不是std::string。有没有办法在通话中打字?而不是:
string send = "Yo!";
print(send);
谢谢。最明显的方法是这样调用函数
print(string("Yo!"));
您需要从中创建一个(临时的)
std::string
对象。嗯,std::string
是一个类,const char*
是一个指针。这是两件不同的事情。从string
到指针很容易(因为它通常包含一个可以直接返回的指针),但另一方面,您需要创建类型为std::string
的对象
我的建议是:采用常量字符串且不修改它们的函数应始终采用
const char*
作为参数。通过这种方式,它们将始终工作-使用字符串文本以及std::string
(通过隐式c_str()
)。您可以编写函数以获取常量std::string&
:
void print(const std::string& input)
{
cout << input << endl;
}
这两种方式都允许您这样称呼它:
print("Hello World!\n"); // A temporary is made
std::string someString = //...
print(someString); // No temporary is made
第二个版本确实要求为std::string
s:
print("Hello World!\n"); // No temporary is made
std::string someString = //...
print(someString.c_str()); // No temporary is made
您应该能够调用print(“yo!”),因为std::string有一个构造函数,它接受const char*。这些单参数构造函数定义了从它们的agument到它们的类类型的隐式转换(除非构造函数声明为显式的,而std::string不是这种情况)。你真的试过编译这段代码吗
void打印(标准::字符串输入)
{
不能使函数接受常量std::string&
而不是按值。这不仅可以避免复制,因此在将字符串接受到函数中时总是首选,而且还可以使编译器从字符[]构造一个临时std::string
你正在给它。:)只需将它转换为常量字符*。
打印((const char*)“Yo!”)就可以了。不是很专业的答案,只是让你知道而已
对于像打印这样简单的东西,您可以在预处理器中定义一种函数,如
#define print(x) cout << x << endl
#define print(x)cout如果我将它们作为const char*传递,我能在成员初始化列表中使用它们吗?现在我正在将字符串传递给一个构造,并通过该构造进行初始化。我认为不存在对c#u str()的隐式调用。我认为您必须显式地进行调用。@Rob Adams,如:string s=“something”;func(s.c_str());对吗?它是显式的,因为它具有可以实例化为变量的属性,s?(不是讽刺,严肃的问题。)@Josh,是的,代码片段就是我的意思。它是显式的,因为您必须指定“.c_str())“--这不会在幕后神奇地发生。唉,我最近看到了太多的字符串类实现。有些有操作符const char*()const
重载,基本上返回c_str()
,但是你是对的,std::string本身没有。Josh,你在使用什么编译器?当我用“g++-Wall-pedantic xx.cc",上面的代码对我来说非常好。不需要强制转换。你用的是什么编译器?错误是什么?你能展示你的全部源代码吗?废话。它在我的工作机器上坏了,我的工作机器是Ubuntu10,使用g++,没有墙壁,没有学究。我刚在家里试过我的OSX机器,它工作得很好,bo在一个类构造中(因为它在工作中被破坏),在一个常规函数中。在MinGW中的g++4.5.0和Ubuntu8.04中的g++4.2.4对我来说都很好。根本没有编译器选项。
print("Hello World!\n"); // A temporary is made
std::string someString = //...
print(someString); // No temporary is made
print("Hello World!\n"); // No temporary is made
std::string someString = //...
print(someString.c_str()); // No temporary is made
void print(std::string input)
{
cout << input << endl;
}
int main()
{
print("yo");
}
#define print(x) cout << x << endl