修改类的私有成员

时间:2016-03-21 22:19:33

标签: class c++11 private

我在改变班级的私人成员时遇到了一些问题。 下面是我的main.cpp

#include "World.h"
#include "GameObject.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <string>

using namespace std;

//function prototypes
void setUserName();


int main()
{
    setUserName();
    return 0;
}
下面的

是我的GameObject.h

#ifndef GAMEOBJECT_H
#define GAMEOBJECT_H
#include <string>

using namespace std;

class GameObject
{
private:
    string userName;

public:
    void setUserName();
};

#endif

下面是我的gameobject.cpp

#include "GameObject.h"
#include <string>
#include <iostream>

using namespace std;

void setUserName()
{
    cout << endl << "Function has been called" << endl;
    cin >> userName;
}

它目前告诉我userName未在此范围内声明,但我认为我在.h文件中声明了 任何提示将非常感谢!提前谢谢!

2 个答案:

答案 0 :(得分:0)

全球职能

void setUserName();

class GameObject内声明的具有相同名称的成员函数是两个不同的函数。只有成员函数才能访问私有成员。如果要在gameobject.cpp中定义成员函数,则需要提供完整的函数名称:

void GameObject::setUserName {
    // ...
}

答案 1 :(得分:0)

您实现了一个函数并将其命名为setUserName(),并且您声明了一个类GameObject的方法,并将其命名为setUserName()。只有该方法才能访问私有变量。但是对于该方法没有实现。

方法实现(在gameobject.cpp中)看起来像:

void GameObject::setUserName()
{
    cout << endl << "Function has been called" << endl;
    cin >> userName;
}

出于您的目的,我认为您甚至根本不需要全局函数setUserName()