这个问题在这里已经有了答案:Whyispassingastringliteralintoachar*argumentonlysometimesacompilererror?(6个回答)关闭9年前.voidf(char*p){}intmain(){f("Hello");//OKautop="Hello";f(p);//errorC2664:'voidf(char*)':cannotconvertparameter1//from'constchar*'to'char*'}代码使用VC++Nov2012CTP编译。§2.14.15StringLiterals,Section7Anarrows
此方法适用于C、C++和Java。我想知道它背后的科学原理。 最佳答案 char的值可以是0-255,其中不同的字符映射到这些值之一。数字也按'0'到'9'的顺序存储,但它们通常也不作为前十个char存储值(value)观。也就是说,字符'0'没有0的ASCII值。0的char值几乎总是\0空字符。在不了解ASCII的情况下,从任何其他数字字符中减去'0'字符将导致原始字符的char值非常简单。所以,这是简单的数学:'0'-'0'=0//Charvalueofcharacter0minuscharvalueofcharacter0/
此方法适用于C、C++和Java。我想知道它背后的科学原理。 最佳答案 char的值可以是0-255,其中不同的字符映射到这些值之一。数字也按'0'到'9'的顺序存储,但它们通常也不作为前十个char存储值(value)观。也就是说,字符'0'没有0的ASCII值。0的char值几乎总是\0空字符。在不了解ASCII的情况下,从任何其他数字字符中减去'0'字符将导致原始字符的char值非常简单。所以,这是简单的数学:'0'-'0'=0//Charvalueofcharacter0minuscharvalueofcharacter0/
当从一个应该使用g++(版本4.7.3)执行隐式转换的函数返回字符串文字时,我看到了一些奇怪的行为。谁能解释为什么下面的代码:#includeclassTest{public:templateTest(constchar(&foo)[N]){printf("Templateconstchararrayconstructor\n");}Test(char*foo){printf("char*constructor\n");}};Testfn(){return"foo";}intmain(){Testt("bar");Testu=fn();return0;}产生结果:Templatecon
当从一个应该使用g++(版本4.7.3)执行隐式转换的函数返回字符串文字时,我看到了一些奇怪的行为。谁能解释为什么下面的代码:#includeclassTest{public:templateTest(constchar(&foo)[N]){printf("Templateconstchararrayconstructor\n");}Test(char*foo){printf("char*constructor\n");}};Testfn(){return"foo";}intmain(){Testt("bar");Testu=fn();return0;}产生结果:Templatecon
这个问题在这里已经有了答案:Isthesizeofastructrequiredtobeanexactmultipleofthealignmentofthatstruct?(9个回答)关闭6年前。alignof(char)可以不是1吗?来自unofficialcppreference.comwiki:Theweakest(smallest)alignmentisthealignmentofthetypeschar,signedchar,andunsignedchar,anditisusually1.“通常”似乎暗示它可能是别的东西。C标准中关于char对齐的唯一规定是(C11N1570
这个问题在这里已经有了答案:Isthesizeofastructrequiredtobeanexactmultipleofthealignmentofthatstruct?(9个回答)关闭6年前。alignof(char)可以不是1吗?来自unofficialcppreference.comwiki:Theweakest(smallest)alignmentisthealignmentofthetypeschar,signedchar,andunsignedchar,anditisusually1.“通常”似乎暗示它可能是别的东西。C标准中关于char对齐的唯一规定是(C11N1570
http://en.cppreference.com/w/cpp/utility/to_charsReference没有说明任何内容,但该示例(对我而言)显然使用了一个以null结尾的字符串,否则它怎么知道在哪里结束,因为std::array::data只返回一个指针。#include#include#includeintmain(){std::arraystr{};std::to_chars(str.data(),str.data()+str.size(),42);std::cout不幸的是,我无法自己测试它,因为AFAIK还没有编译器支持它:https://en.cpprefere
http://en.cppreference.com/w/cpp/utility/to_charsReference没有说明任何内容,但该示例(对我而言)显然使用了一个以null结尾的字符串,否则它怎么知道在哪里结束,因为std::array::data只返回一个指针。#include#include#includeintmain(){std::arraystr{};std::to_chars(str.data(),str.data()+str.size(),42);std::cout不幸的是,我无法自己测试它,因为AFAIK还没有编译器支持它:https://en.cpprefere
为什么在调用函数时unsignedchar会自动提升为int?在下面的示例中,有一个f(int)和一个f(char)函数。编译器将unsignedchar参数强制为char并调用f(char)似乎更合乎逻辑,因为它们具有相同数量的位。它改为调用f(int),即使这意味着将参数提升为具有更多位的类型。任何指向规则定义位置的指针?标准还是编译器/平台特定?#includevoidf(intkey){std::cout产生这个输出:voidf(int)voidf(char)voidf(int) 最佳答案 因为unsignedchar不能用