不能在 C++ 的 main 中定义结构。
#include <iostream>
using namespace std;
int main()
{
struct d
{
char name[20];
int age;
};
struct d s,f;
s = { "agent smith" , 17 };
cout << s.name << " is 17 year old\n";
return 0;
}
每当我编译我的代码时,我都会收到以下错误:-
$ g++ test.cpp
test.cpp: In function ‘int main()’:
test.cpp:25:27: error: no match for ‘operator=’ (operand types are ‘main()::d’ and ‘<brace-enclosed initializer list>’)
s = { "agent smith" , 17 };
^
test.cpp:18:9: note: candidate: constexpr main()::d& main()::d::operator=(const main()::d&)
struct d
^
test.cpp:18:9: note: no known conversion for argument 1 from ‘<brace-enclosed initializer list>’ to ‘const main()::d&’
test.cpp:18:9: note: candidate: constexpr main()::d& main()::d::operator=(main()::d&&)
test.cpp:18:9: note: no known conversion for argument 1 from ‘<brace-enclosed initializer list>’ to ‘main()::d&&’
我的代码有什么问题?我按照书上说的去做(c++ primer Plus 6thED)
最佳答案
尝试显式构造函数:
s = d{ "agent smith" , 17 };
或明确定义initialization
d s{"agent smith", 17};
(假设 C++11,所以使用 GCC - 最好至少是 GCC 6- 编译 with g++ -std=c++11 -Wall -Wextra -g
)
附言。不要费心学习比 C++11 更早的东西。注意 C++17 最近是 approved (2017 年 9 月),但现在还太年轻,无法实现成熟。
关于c++ - 无法在C++中的main中定义结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46252809/