【问题标题】:how to access private array within member function in c++如何在c ++中访问成员函数中的私有数组
【发布时间】:2014-03-29 07:41:50
【问题描述】:

水果.h

class Fruit 
{
    private:
        std::int no[3];
    public:
        void initialize();
        int print_type();
};

水果.cpp

#include "Fruit.h"
void Fruit::initialize() {
    int no[] = {1, 2, 3};
}
int Fruit::print_type() {
    return type[0];
}

Main.cpp

#include <iostream>
#include "Fruit.h"
using namespace std;
int main()
{
    Fruit ff;
    ff.initialize();
    int output = ff.print_type();
    cout << output;
    system("pause");
    return 0;
}

假设所需的指令包含在所有文件中。 此刻,我在取回输出时发现了一个问题,因为它不会导致“0”而是垃圾值。如何在不使用构造函数的情况下修复它?

真诚地希望有人能帮我一个忙。

【问题讨论】:

    标签: arrays function private member


    【解决方案1】:

    这是不使用构造函数和析构函数的方式,希望对你有用。

    #include <iostream>
    
    
    class Fruit 
    {
            private : int* no;
    
            public : void initialize();
            public : void clean();
            public : int print_type();
    };
    
    
    void Fruit::initialize()
    {
            no = new int[ 3 ];
            no[ 0 ] = 1;
            no[ 1 ] = 2;
            no[ 2 ] = 3;
    }
    
    
    int Fruit::print_type()
    {
            return no[ 0 ];
    }
    
    
    void Fruit::clean()
    {
            delete[] no;
    }
    
    
    int main()
    {
            Fruit f;
            f.initialize();
            int o = f.print_type();
            std::cout << o;
                f.clean();
            return 0;
    }
    

    【讨论】:

    • 感谢您的回答。顺便说一句,为什么我们需要使用 int* 类型而不是 int?
    • 因为“no”属性代表一个数组而不是一个整数值,所以你必须让它成为指针。
    • 我做的 int no[3] 怎么样?像这样在类中声明数组是错误的吗?感谢您的耐心。
    • 不,没有错,你可以这样做,但我更喜欢指针.. ;) 如果你以你的方式声明它,那么你将不需要更多的“clean()”方法和“初始化()”中的“新”。
    • 但程序在使用指针时运行良好,但不适用于 int no[3]。那仍然是垃圾值。
    【解决方案2】:

    请阅读 C++ 中的构造函数。您不了解 OOP C++ 中的基本内容。

    #include "Fruit.h"
    void Fruit::initialize() {
        int no[] = {1, 2, 3};
    }
    

    这是不正确的。你最常写this.nono

    int Fruit::print_type() {
        return type[0];
    }
    

    什么是变量type

    【讨论】:

    • 抱歉打错了,应该是“no[0]”
    • 请您指出我的程序出了什么问题,对此感到抱歉。
    • 更好地编写构造函数:( name_of_parama,...){here init}
    • 嗯...我一开始就被限制在没有构造函数的情况下编写。顺便说一句,谢谢你的回答。
    猜你喜欢
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    • 2023-03-14
    • 2023-03-24
    • 1970-01-01
    • 2017-03-11
    相关资源
    最近更新 更多