对象无法访问其私人数据.错误:在这种情况下私有



我是C 新手。我有一个简单的课程,可以存储一个人的名字和年龄。由于某些原因,类的对象无法访问私人数据。当我在下面运行代码时,我会收到错误:test ::名称在此上下文中是私有的。

标题文件

namespace Testing {
    class Test {
        public:
            Test(); // initializes to 0
            Test(int age_, std::string name_);
        private:
            int age;
            std::string name;
    };
}

实现文件:

#include <string>
#include "Test.h"
using namespace std;
using namespace Testing;
Test::Test(){
    age = 26;
    name = "George";
}
Test::Test(int age_, string name_){
    age = age_;
    name = name_;
}

#include <iostream>
#include "Test.h"
using namespace std;
using namespace Testing;
int main(){
    Test test;    
    cout << test.name << endl;
    return 0;
}

您正在尝试从main函数访问类的私人成员。访问私有数据的不是"对象"(尚不清楚您的含义(,函数main试图访问该数据。功能main无法访问您的班级的私人成员。因此错误。

一个对象无法直接访问私人数据。只有类的成员功能才能访问它。因此,尝试编写成员函数(在课堂内部的功能(或将变量(年龄,名称(像

这样

类测试{

公共:

test((;//初始化为0

test(int age_,std :: string name _(;

int age;

std ::字符串名称;

};

请参考使用私人数据成员

或创建朋友功能

使用朋友函数

请参考。

您的问题是尝试访问private数据(名称(,因此您需要使用公共getter或公开成员数据:

std::string Test::getName()const{
    return name;
}

和主要:

//cout << test.name<< endl;
std::cout << test.getName() << endl;

相关内容

最新更新