c ++ - 为字符串分配null [英] c++ - Assigning null to a string

查看:123
本文介绍了c ++ - 为字符串分配null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习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;
}


$ b $ p

所以想创建一个接受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>] 

它基本上抱怨line:mValue = 0;

it's basically complaining about line: mValue=0;

它抱怨这行?我不能为String指定一个空值。

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 ++ - 为字符串分配null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆