#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;
无法正常工作,因为Name
和LastName
未在Meny
类中定义,是否可以定义它们,即使它们是在另一个班级?
答案 0 :(得分:1)
Name
和LastName
不是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;
}
};