为什么这些吸气剂没有返回正确的值? [英] Why do these getters not return the correct values?

查看:90
本文介绍了为什么这些吸气剂没有返回正确的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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: 2019912769



std::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;


这篇关于为什么这些吸气剂没有返回正确的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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