C ++-为std :: string分配null [英] C++ - Assigning null to a std::string
问题描述
我自己学习C ++.我有以下代码,但它给出了错误.
I am learning C++ on my own. I have the following code but it gives error.
#include <iostream>
#include <string>
using namespace std;
int setvalue(const char * value)
{
string mValue;
if(value!=0)
{
mValue=value;
}
else
{
mValue=0;
}
}
int main ()
{
const char* value = 0;
setvalue(value);
cin.get();
return 0;
}
所以要创建一个接受char指针的函数,我想将一个指针传递给它.该函数将指针分配给其成员变量.我故意传递了一个空指针.以下是我遇到的错误:
So want to create a function which accepts char pointers and I want to pass a pointer to it. The function assigns the pointer to its member variable. I'm passing a null pointer intentionally. Following is the error I'm getting:
D:\CPP\TestCP.cpp In function `int setvalue(const char*)':
note C:\Dev-Cpp\include\c++\3.4.2\bits\basic_string.h:422 candidates are: std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(const std::basic_string<_CharT, _Traits, _Alloc>&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
note C:\Dev-Cpp\include\c++\3.4.2\bits\basic_string.h:422 std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(const _CharT*) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
note C:\Dev-Cpp\include\c++\3.4.2\bits\basic_string.h:422 std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(_CharT) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
基本上是在抱怨:mValue = 0;
it's basically complaining about line: mValue=0;
为什么要抱怨这条线?我不能为字符串分配空值吗?
Why is it complaining about this line? I can't assign a null to a String?
推荐答案
我不能为字符串分配空值吗?
I can't assign a null to a String?
不. std :: string
不是指针类型;不能将其设置为"null".它不能表示缺少值,这是使用空指针表示的值.
No. std::string
is not a pointer type; it cannot be made "null." It cannot represent the absence of a value, which is what a null pointer is used to represent.
可以通过为其分配空字符串( s ="
或 s = std :: string()
>)或清除它( s.clear()
).
It can be made empty, by assigning an empty string to it (s = ""
or s = std::string()
) or by clearing it (s.clear()
).
这篇关于C ++-为std :: string分配null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!