qichunren
qichunren

Reputation: 4475

Why can't I set a member value for a class instance?

I am confused about this problem output result:

I am 10 years old. My name is

Why there is blank string after "My name is"?

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

Upvotes: 1

Views: 90

Answers (1)

Josh Kelley
Josh Kelley

Reputation: 58362

There are a few problems here.

int true_name(){
    first_name + last_name;
}

means "add first_name and last_name, discard the result (because you neither returned it nor assigned it to a variable), then return some random result (likely whatever happened to most recently be in the appropriate CPU register)."

Your compiler should have given you warning messages explaining this. For example, GCC gives the following warnings:

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

Make sure that warnings are enabled for your compiler (for example, in GCC, use -Wall from the command line) and pay attention to the warnings.

You should have used something like this:

int true_name(){
    return first_name + last_name;
}

The next problem is in this line:

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

" My name is " is a const char * (pointer to char array, not a std::string class instance), and adding an integer to a pointer means to index that pointer. In this case, you're saying "go true_name() characters into " My name is " and start printing from there." Do this instead:

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

Also, it's "Person," not "Persion."

Upvotes: 5

Related Questions