为什么我不能为类实例设置成员值?

 想要铭记的总是轻易忘却- 发布于 2023-02-10 10:30

我对此问题输出结果感到困惑:

我10岁.我的名字是

为什么"我的名字"之后有空白字符串?

#include 

using namespace std;

class Name {
    int first_name;
    int last_name;

public:
    void setName(int f, int l) {
        first_name = f;
        last_name = l;
    }

    int true_name(){
        first_name + last_name;
    }
};

class Persion {

public:
    int age;
    Name name;

    Persion(){

    }

public:
    void hello(void){
        cout << "I am ";
        cout << age;
        cout << " years old.";
        cout << " My name is " + name.true_name() << endl;
    }
};

int main()
{
    Persion a;
    Name name;
    name.setName(10, 2);
    a.age = 10;
    a.name = name;
    a.hello();
    return 0;
}

Josh Kelley.. 5

这里有一些问题.

int true_name(){
    first_name + last_name;
}

表示"添加first_name和last_name,丢弃结果(因为您既未返回它也未将其分配给变量),然后返回一些随机结果(可能是最近发生在相应CPU寄存器中的事件)."

你的编译器应该给你解释这个的警告信息.例如,GCC发出以下警告:

warning: statement has no effect
warning: control reaches end of non-void function

确保为编译器启用了警告(例如,在GCC中,-Wall从命令行使用)并注意警告.

你应该使用这样的东西:

int true_name(){
    return first_name + last_name;
}

下一个问题是在这一行:

cout << " My name is " + name.true_name() << endl;

"我的名字是"是const char *(指向char数组的指针,而不是std::string类实例),并且向指针添加整数意味着索引该指针.在这种情况下,你说"go true_name()字符为"我的名字是"并从那里开始打印." 改为:

cout << " My name is " << name.true_name() << endl;

此外,它是"人",而不是"人物".

1 个回答
  • 这里有一些问题.

    int true_name(){
        first_name + last_name;
    }
    

    表示"添加first_name和last_name,丢弃结果(因为您既未返回它也未将其分配给变量),然后返回一些随机结果(可能是最近发生在相应CPU寄存器中的事件)."

    你的编译器应该给你解释这个的警告信息.例如,GCC发出以下警告:

    warning: statement has no effect
    warning: control reaches end of non-void function
    

    确保为编译器启用了警告(例如,在GCC中,-Wall从命令行使用)并注意警告.

    你应该使用这样的东西:

    int true_name(){
        return first_name + last_name;
    }
    

    下一个问题是在这一行:

    cout << " My name is " + name.true_name() << endl;
    

    "我的名字是"是const char *(指向char数组的指针,而不是std::string类实例),并且向指针添加整数意味着索引该指针.在这种情况下,你说"go true_name()字符为"我的名字是"并从那里开始打印." 改为:

    cout << " My name is " << name.true_name() << endl;
    

    此外,它是"人",而不是"人物".

    2023-02-10 10:33 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有