本文介绍了为什么这些吸气剂没有返回正确的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
getter返回垃圾数据,即使我在签入调试器时Person实例似乎包含正确的数据:
姓名:P÷☺,年龄: 2019912769标准::的unique_ptr<人> person( new Person()); printf( 名称:%s,年龄:%d \ n,person-> getName(),person-> getAge());
#include < string > 使用 string = std :: string; class 人 { public : Person():name( Alex),年龄( 22 ){} void 更改( const string& name, const int age) { 此 - > name = name; 此 - > age = age; } const string getName(){ return name; } const int getAge(){ return 年龄; } private : string name; int age; };
我尝试过: 在互联网上搜索解释为什么会发生这种情况
解决方案C ++程序应该使用 std :: cout 而不是 printf 。在这种情况下,格式说明符'%s'需要 char * 而不是C ++ 字符串。 你应该得到正确的结果 std :: cout<< 名称:<< person-> getName()<< 年龄:<< person-> getAge()<<的std :: ENDL;
The getters return garbage data even though the "Person" instance seems to contain the right data when I check in the debugger:
Name: P÷ ☺, Age: 2019912769std::unique_ptr<Person> person(new Person()); printf("Name: %s, Age: %d\n", person->getName(), person->getAge());
#include <string> using string = std::string; class Person { public: Person() : name("Alex"), age(22) { } void change(const string& name, const int age) { this->name = name; this->age = age; } const string getName() { return name; } const int getAge() { return age; } private: string name; int age; };
What I have tried: Searching the internet for an explanation why this happens
解决方案 C++ programs should probably use std::cout rather than printf. In this case, the format specifier '%s' expects an char * not a C++ string. You should get the right results with std::cout << "Name: " << person->getName() << " Age: " << person->getAge() << std::endl;更多推荐
为什么这些吸气剂没有返回正确的值?
发布评论