C++ C++;:从外部访问类成员变量

C++ C++;:从外部访问类成员变量,c++,c++11,C++,C++11,我在头文件中定义了一个类,如下所示: // picture.hpp: class Picture { public: int count; void draw(); }; 对应的实现源文件: // picture.cpp import "picture.hpp"; Picture::draw() { // some code someFunction(); } void someFunction() { //some code // can I u

我在头文件中定义了一个类,如下所示:

// picture.hpp:
class Picture {
  public:
  int count;
  void draw();
};
对应的实现源文件:

// picture.cpp
import "picture.hpp";
Picture::draw() {
  // some code
  someFunction();
}

void someFunction() {
 //some code
 // can I use variable "count" declared in Picture class in this function
}

someFunction()可以访问类成员图片吗?

正如标题所说的您希望从外部访问类成员。可能有很多方法。例如:使类成员变为vaiable&函数都是静态的,然后调用它而不创建类的实例,即使它是私有的。
但是,如果您不想使成员函数成为静态的,并且从外部使用类成员变量,那么您可以使用友元函数。现在友元函数可以做什么呢?您可以阅读它,也可以是任何符合您期望的内容。现在,如果您使用friend函数,则必须在类内指定。如下所示

class Picture
{
public:
    int count;
    void draw(Picture obj);
    friend void someFunction(/*other parameters if you have*/Picture obj); //as global friend
};
可以在somefunction()中执行成员变量的操作,如下所示:

void someFunction(/*other parameters if you have*/ Picture obj)
{
    //some code
    // can I use variable "count" declared in Picture class in this function
    printf("%d", obj.count);
    return;
}
void Picture::draw(/*other parameters if you have*/ Picture objA)
{
    // some code
    someFunction(/*other parameters if you have*/ objA);
}
int main()
{
    Picture pic1;
    pic1.draw(pic1);
    return 0;
}
设计层面的问题来了。根据您的代码,您希望在成员函数draw()中调用somefunction(),但现在somefunction()需要一个对象作为参数。因此,如果您在draw()成员函数中传递对象,则可以完成此操作。如下所示:

void someFunction(/*other parameters if you have*/ Picture obj)
{
    //some code
    // can I use variable "count" declared in Picture class in this function
    printf("%d", obj.count);
    return;
}
void Picture::draw(/*other parameters if you have*/ Picture objA)
{
    // some code
    someFunction(/*other parameters if you have*/ objA);
}
int main()
{
    Picture pic1;
    pic1.draw(pic1);
    return 0;
}
最后,调用main函数。如下所示:

void someFunction(/*other parameters if you have*/ Picture obj)
{
    //some code
    // can I use variable "count" declared in Picture class in this function
    printf("%d", obj.count);
    return;
}
void Picture::draw(/*other parameters if you have*/ Picture objA)
{
    // some code
    someFunction(/*other parameters if you have*/ objA);
}
int main()
{
    Picture pic1;
    pic1.draw(pic1);
    return 0;
}
现在,如果不创建实例,您就不能在类的成员之外调用(静态除外)[]因此,这里我做了两件事,我将所有参数作为“按值传递”,并将somefunction()作为该类的朋友。现在您可以选择忽略上述整个过程,因为您将count变量声明为public。所以,只要使用instance&dot运算符,就可以在类成员函数中的任何位置使用它,但如果您希望在类之外使用成员变量,则上述过程可能会对您有所帮助。


让我知道它是否对您有帮助。

这不是
import
的工作原理。你的意思是“包括”?每一个类型为
Picture
的对象都有自己的名为
count
的成员,
someFunction
如何说出要查看哪个
Picture
呢?@aschepper my bad!其#包括而非进口。类成员计数可用于draw()实现。我仍然可以将它从draw()传递到someFunction()并使用它。但是仍然想知道是否还有其他方法。因为
count
public:
您可以直接访问它,但必须通过类的实例访问它。