Domanda

Fruit.h

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

Fruit.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;
}

Assume the required directives are included inside all the files. At this moment, I find a problem when getting back the ouput since it will not result in "0" but a garbage value. How can I fix it without using constructor?

Sincerely hope that someone would do me a favor.

È stato utile?

Soluzione

This is the way that doesn't use constructors and destructors, I hope you find it useful.

#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;
}

Altri suggerimenti

Please, read about constructor in C++. You don't know about the elementary things in OOP C++.

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

This is not correctly. You most write this.no or no.

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

What is variable type?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top