【发布时间】:2025-12-26 01:20:13
【问题描述】:
我对 c++ 很陌生,以前我用 Python 编程。我正在学习如何定义
c++ 中的函数,我认为它有点像 python def 函数。我不断收到错误:
no match for call to `(std::string) (const char[4])`.
我正在使用开发 C++。这是我的代码:
#include <iostream>
int main()
{
using namespace std;
cout << "Enter a number: "; // ask user for a number
int x;
cin >> x; // read number from console and store it in x
cout << "You entered " << x << endl;
cout << "\n" << "Enter 'a': ";
string y;
cin >> y;
if (y=="a"){
cout << "You typed 'a'!!!";
int z;
cin >> z;
return 0;
}
else {
cout << "You didn't type 'a'!!!" << endl;
}
string word;
string subfunction(word);
{
cout << word << endl;
}
subfunction("abc");
return main();
}
最后,您可能已经注意到subfunction 的声明和定义。如果我是用 python 写的,那就是:
def subfunction(word):
print(word)
subfunction('abc')
【问题讨论】:
-
看来你是python背景的,你不能在c++的main体中放一个函数。因此,您至少必须将
subfunction移到主循环之外。此外,出于各种原因,最好改掉using namespace std的习惯。 -
一些建议 -- 使用您对另一种计算机语言的知识来解决可以应用于 C++ 的逻辑问题 -- 不要使用您对另一种语言的知识来学习 C++ 本身。
-
return main();?!?认真的吗? -
请不要向我们询问您在学习 C++ 时遇到的每一个错误。先读这本书——仔细,然后来。软件问题在这里发帖是可以的,只要问题不是“我还没有学过语言语法”即可。
标签: c++