我对此问题输出结果感到困惑:
我10岁.我的名字是
为什么"我的名字"之后有空白字符串?
#includeusing 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;
此外,它是"人",而不是"人物".
这里有一些问题.
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;
此外,它是"人",而不是"人物".