我遇到了一个我自己无法真正解决的非常奇怪的问题,它考虑了简单的 C++ 程序。
我知道我可以而且可能应该使用 setFunction 而不是 list 来初始化变量,但我这样做只是为了了解它是如何工作的。
给大家介绍一下我的代码,这个是完全可以编译的(这个和那个的区别已经标出来了):
#include <iostream>
#include <string>
using namespace std;
class SimpleClass
{
private:
string name;
public:
SimpleClass(string z): name(z)
{
string getName(z); // ***HERE WE HAVE getName() function with return type string
}
string getName()
{
return name;
}
};
int main(void)
{
SimpleClass object("Pussycat");
cout << object.getName() << endl;
}
这个不起作用,因为我没有指定函数 getName() 的返回类型,它用于返回值名称:
#include <iostream>
#include <string>
using namespace std;
class SimpleClass
{
private:
string name;
public:
SimpleClass(string z): name(z)
{
getName(z); // *** WITHOUT STRING TYPE BEFORE FUNCTION NAME
}
string getName()
{
return name;
}
};
int main(void)
{
SimpleClass object("Pussycat");
cout << object.getName() << endl;
}
知道为什么第二个不起作用吗?
最佳答案
在这段代码中,
SimpleClass(string z): name(z)
{
string getName(z); // ***HERE WE HAVE getName() function with return type string
}
您有一个名为 getName
且类型为 string
的函数局部变量。它使用 z
构造并被丢弃。与类成员函数getName
无关。
在这段代码中,
SimpleClass(string z): name(z)
{
getName(z); // *** WITHOUT STRING TYPE BEFORE FUNCTION NAME
}
您正在使用 z
作为参数调用成员函数 getName
,但编译失败,因为 getName()
没有参数.
关于构造函数中的函数的 C++ 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25898192/