C++ C2039-函数不是类的成员
我正在对模板类进行一些实验,发现了以下错误:C++ C2039-函数不是类的成员,c++,class,templates,C++,Class,Templates,我正在对模板类进行一些实验,发现了以下错误: Error C2039 'getName': is not a member of 'Person<T> 错误C2039“getName”:不是“Person”的成员 这是我的班级结构: struct professor { static const char name[]; static const age = 50; }; struct student { static const char na
Error C2039 'getName': is not a member of 'Person<T>
错误C2039“getName”:不是“Person”的成员
这是我的班级结构:
struct professor
{
static const char name[];
static const age = 50;
};
struct student
{
static const char name[];
static const age = 21;
};
const char professor::name[] = "Jules";
const char student::name[] = "Michael";
// Please make the Person template class here.
template <class T>
class Person
{
public:
Person();
char[] getName();
private:
T & m_Person;
};
template<class T>
Person<T>::Person()
{
m_Person= T;
}
template<class T>
char* Person<T>::getName()
{
return m_Person.name;
}
struct教授
{
静态常量字符名[];
静态常数=50;
};
结构学生
{
静态常量字符名[];
静态常数=21;
};
康斯特·查尔教授:姓名[]=“朱尔斯”;
const char student::name[]=“Michael”;
//请在这里创建Person模板类。
样板
班主任
{
公众:
人();
char[]getName();
私人:
T&m_人;
};
样板
Person::Person()
{
m_Person=T;
}
样板
char*Person::getName()
{
返回m_Person.name;
}
你知道失败的是什么吗
事实上,我不知道类定义等是否正确,因为我是模板类的新手,所以如果您看到任何其他错误,如果您警告我,那就太好了
谢谢你,我希望你能帮助我 自始至终修复编译错误
char[]
不是有效的返回类型,getName()
的函数定义无法编译,这就是为什么会出现错误
您也缺少了
您的代码有点混乱,我想您需要这样的代码:
#include <string>
#include <iostream>
struct professor
{
std::string name;
int age;
};
struct student
{
std::string name;
int age;
};
template <class T>
class Person
{
public:
Person(const T& person) : m_Person(person) {}
std::string getName()
{
return m_Person.name;
}
private:
T m_Person;
};
int main() {
student s{"Michael", 21};
Person<student> p(s);
std::cout << p.getName();
return 0;
}
#包括
#包括
结构教授
{
std::字符串名;
智力年龄;
};
结构学生
{
std::字符串名;
智力年龄;
};
样板
班主任
{
公众:
人(const T&Person):m_Person(Person){}
std::string getName()
{
返回m_Person.name;
}
私人:
T m_人;
};
int main(){
学生s{“Michael”,21};
个人p(s);
std::里面有很多奇怪的东西。例如,年龄是多少?char*Person::getName()
vschar[]getName();
。看到这两种返回类型的区别了吗?现在我想了想,我不确定你能返回char[]
.Hack test:。编译器不喜欢它。相反,返回char*
。编译器还应该对m_Person=T;
咆哮。这是给变量分配类型。我错过了,当你实例化Person
时可能会错过。我将你的答案标记为正确。谢谢!是的,我现在在“m_Person=T”上有一个错误。错误是:引用必须初始化。如果它们真的是noob问题,很抱歉。我只是从C++开始,通常情况下,你不能有空引用,所以你必须在构造函数初始值设定项列表中初始化它,但我认为这里不需要引用。在答案中添加了一些代码。
#include <iostream>
struct S {
static const int x = 42;
};
template <typename T>
struct A {
int getValue() {
return T::x;
}
};
int main() {
A<S> a;
std::cout << a.getValue();
return 0;
}