我有一个模拟窗口的程序;所以我将窗口的内容存储在成员数据 content 中,它是 std::string 类型:
class Window {
using type_ui = unsigned int;
public:
Window() = default;
Window(type_ui, type_ui, char);
void print()const;
private:
type_ui width_{};
type_ui height_{};
char fill_{};
std::string content_{};
mutable type_ui time_{};
};
Window::Window(type_ui width, type_ui height, char fill) :
width_{ width }, height_{ height }, fill_{ fill },
content_{ width * height, fill } { // compile-time error here?
//content( width * height, fill ) // works ok
}
void Window::print()const {
while (1) {
time_++;
for (type_ui i{}; i != width_; ++i) {
for (type_ui j{}; j != height_; ++j)
std::cout << fill_;
std::cout << std::endl;
}
_sleep(1000);
std::system("cls");
if (time_ > 10)
return;
}
}
int main(int argc, char* argv[]) {
Window main{ 15, 25, '*' };
main.print();
std::string str{5u, '*'}; // compiles but not OK
std::string str2(5u, '*'); // compiles and OK
cout << str << endl; // ♣* (not intended)
cout << str2 << endl; // ***** (ok)
std::cout << std::endl;
}
正如您在上面看到的那样,我无法使用 curly-braces-initializer-list 初始化成员 content,编译器会提示“缩小类型”。但它适用于“直接初始化”。
为什么我不能在 Constructor-initializer-list 中使用上面的 Curly-brace-initialization-list 来调用 std::string(size_t count, char)。
为什么这个 std::string str{5u, '*'};//编译但不正常 工作但给出的输出不是预期的?
对我来说很重要的事情是,为什么相同的初始化在构造函数成员初始化列表中不起作用,但在 main 中起作用(结果不是预期的)?
最佳答案
首先,因为 std::string的构造函数 sts::string(size_t count, char)是显式的,因此您不能隐式调用它。
其次,您没有调用 std::string(size_t, char)在 content{width * height, fill}但实际上你正在调用 std::string(std::initializer_list<char>) .因此表达式 width * height产生一个 unsigned int 然后隐式转换为 char 这是“相关类型”因此例如你通过了 Window main{ 15, 25, '*' };哪个产量 (char)15 * 25 = (char)375这是未定义的行为,因为此值溢出 signed char .你可能会在你的机器上得到“♣”或其他值作为初始化列表中的第一个元素但它是未定义的行为并且“”作为初始化列表中的第二个元素。因此,您传递的是 std::initializer_list{'♣', ''}。
第二个问题的答案:“对我来说很重要的事情是为什么相同的初始化不适用于构造函数成员初始化列表但适用于 main(不是预期的结果)?” :
事实上它与“Constructor-member-initializer-list”没有任何关系但实际上考虑一下:
char c{ 127 }; // the maximum integer positive value that a signed char can hold so no narrowing conversion here. So it is OK.
char c2{ 128 }; // Now 128 overflows the variavle c2. c2 is of type char and as you know it can hold positive values in range 0 to 127 and negative -1 to -128
unsigned char uc{ 255 }; // ok because an unsigned char can hold 255
unsigned char uc2{ 300 }; // error as the error above. An unsigned char can hold 255 as max positive value.
unsigned char uc3 = 321; // ok // ok but you may get a warning. a Copy-initialization is not safe.
cout << uc3 << endl; // you may get `A`. 321 % 256 = 65. 65 % 256 = 65. 65 in ASCII in some implementations it represents the character "A".
虽然上面的uc3溢出不是什么好事,但是结果是明确的。 (溢出未签名的 Xtype)。
但是看看这个:
char c3 = 321; // signed char overflows
cout << c3 << endl; // you may get "A" and think it is correct.
在它上面是未定义的行为。永远不要尝试溢出签名类型。
constexpr int i = 10;
constexpr int j = 5;
std::string str{ i * j, 'f' }; // ok as long as the values are constexpr and don't cause any narrowing conversion this value: 10 * 5 = 50 which is a well defined signed-char value.
int i = 10;
int j = 5;
std::string str{ i * j, 'f' }; // error. the values of i and j are not constant thus it may overflow a signed char causing narrowing conversion thus the compiler is wise enough to prevent this initialization.
关于c++ - 为什么我不能用统一初始化来初始化一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55884699/
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
在我的Rails(2.3,Ruby1.8.7)应用程序中,我需要将字符串截断到一定长度。该字符串是unicode,在控制台中运行测试时,例如'א'.length,我意识到返回了双倍长度。我想要一个与编码无关的长度,以便对unicode字符串或latin1编码字符串进行相同的截断。我已经了解了Ruby的大部分unicode资料,但仍然有些一头雾水。应该如何解决这个问题? 最佳答案 Rails有一个返回多字节字符的mb_chars方法。试试unicode_string.mb_chars.slice(0,50)
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl
大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje
我试图获取一个长度在1到10之间的字符串,并输出将字符串分解为大小为1、2或3的连续子字符串的所有可能方式。例如:输入:123456将整数分割成单个字符,然后继续查找组合。该代码将返回以下所有数组。[1,2,3,4,5,6][12,3,4,5,6][1,23,4,5,6][1,2,34,5,6][1,2,3,45,6][1,2,3,4,56][12,34,5,6][12,3,45,6][12,3,4,56][1,23,45,6][1,2,34,56][1,23,4,56][12,34,56][123,4,5,6][1,234,5,6][1,2,345,6][1,2,3,456][123
在我的gem中,我需要yaml并且在我的本地计算机上运行良好。但是在将我的gem推送到rubygems.org之后,当我尝试使用我的gem时,我收到一条错误消息=>"uninitializedconstantPsych::Syck(NameError)"谁能帮我解决这个问题?附言RubyVersion=>ruby1.9.2,GemVersion=>1.6.2,Bundlerversion=>1.0.15 最佳答案 经过几个小时的研究,我发现=>“YAML使用未维护的Syck库,而Psych使用现代的LibYAML”因此,为了解决