C++中Human类无法调用Brain类identify()函数求助
问题描述
正在通过Git上的习题巩固C技能,要求禁止使用friend关键字,采用纯C风格。目前无法在Human类中调用其Brain成员的identify()函数,代码还存在其他语法和逻辑问题,需要修正以满足以下题目要求:
- 创建Brain类,其
identify()函数返回自身内存地址(十六进制,带0x前缀)。 - 创建Human类,拥有一个与自身生命周期绑定的
const Brain成员属性,Human的identify()函数需调用Brain的identify()并返回结果。 - 确保以下main代码编译通过并输出两个相同的地址:
int main(){ Human bob; std::cout << bob.identify() << "\n"; std::cout << bob.getBrain().identify() << "\n"; }
原代码的错误点
- Human构造函数错误:
const成员变量humanBrain必须通过初始化列表初始化,不能在构造函数体内赋值;且new Brain返回指针,不能直接赋值给Brain对象类型。 - Human::identify逻辑错误:试图将
identify()的返回值(std::string)赋值给Brain对象,类型完全不匹配;没有直接调用humanBrain.identify(),反而手动拼接地址,违背题目要求;取对象地址的方式错误,const Brain * ptr = humanBrain是对象转指针的非法操作,正确应为&humanBrain。 - Brain::identify错误:输出的是指针
bPtr自身的地址(&bPtr),而非Brain对象的地址(bPtr);手动添加"0x"多余,因为流输出指针会自动带0x前缀;identify()未声明为const成员函数,无法被const的Brain对象调用。 - Human类缺失必要函数:题目main代码调用了
bob.getBrain(),原代码未实现该函数。 - Brain的identify返回值修饰冗余:
const std::string identify()中的const修饰返回值无意义,应改为非const返回,并添加const成员函数修饰。
修正后的完整代码
Brain.h
#pragma once #include <string> class Brain { int age; std::string gender; public: Brain(); std::string identify() const; // 声明为const成员函数 };
Brain.cpp
#include "Brain.h" #include <sstream> Brain::Brain() : age(10), gender("male") // 初始化列表初始化成员 {} std::string Brain::identify() const { std::ostringstream oss; oss << this; // 直接输出当前对象的地址,自动带0x前缀 return oss.str(); }
Human.h
#pragma once #include "Brain.h" #include <string> class Human { const Brain humanBrain; // const成员 public: Human(); std::string identify() const; // 同样声明为const成员函数 const Brain& getBrain() const; // 添加getBrain函数,返回const引用 };
Human.cpp
#include "Human.h" Human::Human() : humanBrain() // 初始化列表初始化const成员 {} std::string Human::identify() const { return humanBrain.identify(); // 直接调用Brain的identify并返回结果 } const Brain& Human::getBrain() const { return humanBrain; // 返回const引用,避免拷贝 }
测试main函数
#include "Human.h" #include <iostream> int main(){ Human bob; std::cout << bob.identify() << "\n"; std::cout << bob.getBrain().identify() << "\n"; return 0; }
说明
- 所有需要被
const对象调用的成员函数都声明为const,符合C++常量正确性原则。 - Human的
const成员humanBrain通过初始化列表完成初始化,符合const成员的初始化规则。 getBrain返回const引用,避免不必要的对象拷贝,同时保证成员不被外部修改。- Brain的
identify直接输出this指针,流会自动处理十六进制格式并添加0x前缀,无需手动拼接。
内容的提问来源于stack exchange,提问作者agile_flow
相关产品推荐
相关产品推荐

