You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Player类Getter与Setter方法调用错误求助

修复你的Player类名称修改功能问题

嘿,我来帮你搞定这个问题!你遇到的两个编译错误都是因为对类成员函数的调用方式理解有误,咱们一步步来修正:

错误原因分析

  • 错误C2679:你写的cin >> player.setName;是错的。setName是Player类的成员函数,不是一个可以直接接收输入的变量。cin需要的是一个可被赋值的变量(左值),而不是函数名。
  • 错误C3867:player.getName同样是成员函数,调用它必须加上括号(),否则编译器会认为你想获取这个函数的指针,而不是调用它获取玩家名称。

修正后的主函数代码

// Thomas' Game.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include "Player.h"
#include <fstream>
#include <istream>
using namespace std;

int main() {
    Player player;
    string inputName; // 先定义一个变量存储用户输入
    cout << "Hello traveller, could I ask you your name?";
    cin >> inputName; // 把输入读到变量里
    player.setName(inputName); // 调用setName函数传入输入的名字
    cout << "Hello " << player.getName() << endl; // 调用getName函数要加括号
    return 0;
}

额外小建议

尽量不要在头文件(比如Player.h)里使用using namespace std;,因为头文件会被其他文件包含,容易引发命名冲突。可以把Player.h里的using namespace std;去掉,换成std::前缀,比如:

#pragma once
#include <iostream>
#include <string>

class Player {
private:
    std::string playerName = "";
    std::string playerRace = "";
    int playerAge = 0;
public:
    void setName(std::string);
    std::string getName();
    void setRace(std::string);
    std::string getRace();
    void setAge(int);
    int getAge();
};

这样你的代码就能正常编译运行啦!

内容的提问来源于stack exchange,提问作者Tomhass

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:34:30