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

时间:2013-12-16 13:25:07

标签: c++

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

我今年10岁。我的名字是

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

#include <iostream>

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;
}

1 个答案:

答案 0 :(得分: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;

此外,它是“人”,而不是“Persion。”