且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在另一个类中使用成员变量

更新时间:2023-01-07 09:16:12

首先,不要访问成员其他类的变量直接。这是非常糟糕的做法。您的成员变量应该是私有的,您应该声明方法(函数)来返回值。这可以防止调用者将它们设置为无效值。



第二,当你到达那条线时,为什么会员变量被破坏?他们不应该。更有可能的是你没有初始化它们。



您正在使用默认构造函数来创建LoadImage对象。这是你想要的,或者你想指定文件路径或资源ID,例如?



你有一个正确初始化成员的默认构造函数吗?变量(可能为零)。



这个怎么样,例如:

In the first place, don''t access member variables of other classes directly. This is very bad practice. Your member variables should be private and you should declare methods (functions) to return the value. This prevents a caller from setting them to invalid values.

In the second place, why are the member variables "destroyed" when you reach that line? They shouldn''t be. What is more likely is that you haven''t initialised them.

You are using the default constructor to create the LoadImage object. Is this what you want, or do you want to specify a file path or a resource id, for example?

Do you have a default constructor that correctly initialises the member variables (probably to zero).

How about this, for example:
class LoadImage
{
public:
    LoadImage()
    :   width(0),
        height(0),
        imgData(NULL)
    {
    }

    LoadImage
        (
        const std::string& filePath
        )
    :   width(0),
        height(0),
        imgData(NULL)
    {
        // load image from filePath into imgData and set height and width accordingly.
    }

    virtual ~LoadImage()
    {
        if (NULL != imgData)
        {
            // Free imgData according to how you initialised it
            // And set it back to null (not important in this case, but it is good practice)
            imgData = NULL;
        }
    }

    inline int GetHeight() const
    {
        return height;
    }

    inline int GetWidth() const
    {
        return width;
    }

    // ......

private:
    int width;
    int height;
    BYTE* imgData;
};


您声明LoadImage但从未创建关联对象。您需要创建对象以便可以访问成员数据,例如:



LoadImage img = new LoadImage();

int lwidth = img.Width;



否则你试图访问受保护的内存,或者它甚至可能是一些随机值,因为它没有初始化。
You declare LoadImage but you never create the associated object. You need to create the object so that you can access the member data, like:

LoadImage img = new LoadImage();
int lwidth = img.Width;

Otherwise you are attempting to access protected memory or it could even be some random value because its not initialized.