仅在班级

时间:2018-05-26 10:36:04

标签: c++ class c++11 inheritance

#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <string>
using namespace std;
class Meny
{
public:
    void Meny2()
    {
        cout << "Welcome " << Name << LastName;
    }
};

class Kund
{
public:
    string  Name, LastName, personnummer;

    void LoggaIn()
    {
        cout << "Please enter your full name: " << endl;
        cin >> Name >> LastName;
        cout << "Please enter your social security number: " << endl;
        cin >> personnummer;
    }
};

所以目前cout << "Welcome " << Name << LastName;无法正常工作,因为NameLastName未在Meny类中定义,是否可以定义它们,即使它们是在另一个班级?

1 个答案:

答案 0 :(得分:1)

NameLastName不是Meny的属性。它们是Kund的属性。因此无法访问这些属性。你必须以某种方式使它可以访问。

#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <string>
using namespace std;

class Kund
{
public:
    string  Name, LastName, personnummer;

    void LoggaIn()
    {
        cout << "Please enter your full name: " << endl;
        cin >> Name >> LastName;
        cout << "Please enter your social security number: " << endl;
        cin >> personnummer;
    }
};

class Meny
{
public:
    void Meny2(const Kund& k) const
    {
        cout << "Welcome " << k.Name << k.LastName;
    }
};

或子类

class Meny: public Kund
{
public:
    void Meny2() const
    {
        cout << "Welcome " << Name << LastName;
    }
};

或模板

template <typename T>
class Meny: public T
{
public:
    void Meny2() const
    {
        cout << "Welcome " << Name << LastName;
    }
};

或在功能中使用模板

class Meny
{
public:
    template <typename T>
    void Meny2(const T& k) const
    {
        cout << "Welcome " << k.Name << k.LastName;
    }
};