c++ - 成员函数无法访问私有(private)变量未在范围类中声明

标签 c++ private-members

//This is the header file (header.h)
class about{

char w[10][40];

public:
void get(const char core[ ][2000], int num);


};

~ ~

//This is the cpp file (program.cpp)
 #include "header.h"
 #include <cstring>


void about::get(const char core[ ][2000], int num){

char data[2000];


strcpy(w[0], data);


}

我得到 program.cpp:13: error: 'w' was not declared in this scope

我正在尝试从 data 执行 strcpy,其中包含一些信息到 w ,它来自类的私有(private)部分,并使用成员函数来访问他们。

我不确定我是否忘记了什么以及为什么我无法访问它们。

感谢 Sergey Vakulenko 最后的回答

头文件的顺序非常重要。

应该是

 #include <cstring>
 #include "header.h"

不是

 #include "header.h"
 #include <cstring>

最佳答案

将这些 header 添加到您的 cpp 文件中:

#include <stdio.h>
#include <string.h>
#include "nameofheader.h"

编辑(更完整的解释):

对我来说,那个例子不会给出任何错误:

1.h:

class about{

char w[10][40];

public:
void get(const char core[ ][2000], int num);


};

1.cpp:

#include <stdio.h>
#include <string.h>
#include "1.h"
//This is the cpp file (program.cpp)

void about::get(const char core[ ][2000], int num){

char data[2000];


strcpy(w[0], data);


}

int main (int argc, char** argv) {

return 0;
}

用 g++ 完成:

g++ 1.cpp -o 1

关于c++ - 成员函数无法访问私有(private)变量未在范围类中声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10971083/

相关文章:

C++ - 在 header 中初始化变量与使用构造函数

c++ - Dijkstra 算法中的优先级队列

c++ - Allegro 5.0 - 为什么我会收到链接器错误?

c++ - 这种递归方法有什么问题?计算 2 个 vector 中相同索引中的匹配元素的数量

c++ - 从静态方法访问类的私有(private)成员变量

c++ - 访问基类的私有(private)变量时派生类出错

c++ - 重载运算符 << Boost Log

unit-testing - 当您使用您对私有(private)方法的了解来选择测试用例时,您是否明确地对私有(private)方法进行了单元测试

c++ - 为什么在一种情况下使用私有(private)内部类作为参数在 header 中出错,而在另一种情况下在调用函数中出错?

entity-framework - 映射私有(private)属性时的问题