C++类与对象代码报错求助:修复operator<<错误并实现指定输出
问题分析与修复
首先你的理解有一点偏差:类是数据与操作数据的函数的封装体,不止是函数分组;对象是类的实例,通过对象可以访问类的成员(包括成员变量和成员函数)。
你的代码存在几处问题,导致编译错误和运行不符合预期:
错误点说明
- 函数定义与调用不匹配:
PrintName::studentName()定义时没有参数,但main里调用时传入了"Mark"和"Santo"两个参数,这会导致编译报错。 - 错误引用函数名作为输出内容:
studentName()函数里写的cout<<studentName,这里的studentName是函数本身的名字(本质是函数指针),cout没有对应的输出重载,这就是你看到的第15行operator<<不匹配错误。 - 缺少名字的传递逻辑:没有渠道把
main里的名字传递到函数中输出。
修复后的代码
#include <iostream> #include <string> // 处理字符串需包含此头文件 using namespace std; class PrintName{ public: // 修改函数,接收两个字符串参数 void studentName(const string& firstName, const string& lastName){ cout<<"Name : "<<firstName<<" "<<lastName<<endl; } }; class MathClass{ public: void multiplicationFunc(int x, int y){ cout<<"Result : "<<(x*y)<<endl; } }; int main() { cout<<endl; PrintName PN; PN.studentName("Mark", "Santo"); // 调用与函数定义匹配 MathClass MC; MC.multiplicationFunc(10,5); }
进阶优化(类封装数据的写法)
如果希望类存储学生名字(而非每次调用传参),可以给PrintName添加成员变量,更贴合类的封装特性:
#include <iostream> #include <string> using namespace std; class PrintName{ private: string firstName; string lastName; public: // 构造函数初始化名字 PrintName(const string& fName, const string& lName) : firstName(fName), lastName(lName) {} void studentName(){ cout<<"Name : "<<firstName<<" "<<lastName<<endl; } }; int main() { cout<<endl; PrintName PN("Mark", "Santo"); // 初始化对象时传入名字 PN.studentName(); MathClass MC; MC.multiplicationFunc(10,5); }
内容的提问来源于stack exchange,提问作者Yuki mB
相关产品推荐
相关产品推荐

