繁体   English   中英

OOP - A member function of one class inside a member function of another class

[英]OOP - A member function of one class inside a member function of another class

另一个class中的一个class的成员function在另一个ZA2F2ED4F8EBC2CBB4C21A29DC4的成员function中。

你好。 我尝试了成员 function method()的内容; class B打印在成员 function method()中; class A ,但我没有成功。 尝试编译时出现错误。

你有什么建议来解决这个问题吗?

#include <iostream>
#include <string>

using namespace std;

class A { 
public:
    void method();
};

class B { 
public:
    int n = 6;
    int x;
    string** plantas;
    string cantidad, m_nombre, m_familia, m_genero, m_luz, m_riego, m_fertilizante;
    static void method();
};

void A::method(){
    cout << "Inicio" << endl;
    B::method();
    cout << "Final" << endl;
}

void B::method(){
    cout << "\n \t ¿Cuántas plantas registrarás?" << endl;
    getline(cin, cantidad);
    x = stoi(cantidad);
    plantas = new string * [n];

    cin.ignore();
    for (int i = 0; i < x; i++) {
        plantas[i] = new string[n];
        cout << "\t Nombre: ";
        getline(cin, m_nombre);
        cout << "\t Familia: ";
        getline(cin, m_familia);
        cout << "\t Genéro: ";
        getline(cin, m_genero);
        cout << "\t Ubicación (Luz/Sombra): ";
        getline(cin, m_luz);
        cout << "\t Periodo de riego: ";
        getline(cin, m_riego);
        cout << "\t Periodo de fertilización: ";
        getline(cin, m_fertilizante);
        plantas[i][0] = m_nombre;
        plantas[i][1] = m_familia;
        plantas[i][2] = m_genero;
        plantas[i][3] = m_luz;
        plantas[i][4] = m_riego;
        plantas[i][5] = m_fertilizante;
    }

    for (int i = 0; i < x; i++) {
        delete[] plantas[i];
    }

    delete[] plantas;

    system("pause");
}

int main(){
    A a;
    a.method();
    
    return 0;
}

Static 方法参考 class 本身; 非静态方法作用于 class 的实例。 这就是为什么非静态成员函数有一个隐式(不可见)的第一个参数:它们作用的实例。

因此,使用非静态方法,您可以访问非静态成员(字段和函数)和 static 成员(同样两者),因为您有一个实例并且可以访问 class(全局)属性。

使用static方法,您没有要处理的实例,因此您只能使用static成员(字段和函数)。

在您的代码中,您尝试访问 static 成员 function B::method()内的非静态成员B::plantas 这行不通。 要么你也让B::plantas static ,或者你让B::method()非静态并创建一个B的实例来使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM