gpt4 book ai didi

c++ - 只定义在一个类中

转载 作者:行者123 更新时间:2023-11-28 04:39:33 24 4
gpt4 key购买 nike

#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;不会工作因为NameLastNameMeny 中未定义类,有没有办法让它们被定义,即使它们是在另一个类中定义的?

最佳答案

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

关于c++ - 只定义在一个类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50541838/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com