提前抱歉可能是一个糟糕的职位。我已经在 stackoverflow 上搜索了可以回答我问题的现有帖子,但是尽管这里的许多帖子都是相似的,但它们似乎都不适用于我的情况。 我有 struct Node,被设计成一个容器。类角色,它有角色的名字和力量。 由于某种原因,没有默认构造函数,代码崩溃并出现错误:
#include <sstream>
#include <string>
#include <vector>
#include <iostream>
class Characters {
public:
int power;
std::string name;
Characters(int power, const std::string &name) : power(power), name(name) {}
// Characters() : power(0), name("") {}
//without above line, the code crashes with error: no matching function for call to 'Characters::Characters()' 39 | Node (const Node<T> &other) {
Characters(const Characters &other) {
power=other.power;
name = other.name;
}
};
template <typename T>
struct Node {
T val;
Node (const T &val) : val(val) {}
Node (const Node<T> &other) {
val= other.val;
}
};
int main() {
using namespace std;
Node<Characters> n1(Characters(4, "meh"));
Node<Characters> n2=n1;
return 0;
}
我不知道为什么在没有默认构造函数的情况下会发生这种情况。我可能只是不擅长使用谷歌,但我搜索的所有内容似乎都没有解决我的问题。
任何帮助将不胜感激。谢谢!
感谢 463035818_is_not_a_number 指出这一点!
以下:
Node (const Node<T> &other) {
val= other.val;
}
应该换成这个。
Node (const Node &other) : val(other.val) { }
我误解了成员初始化列表的用法和属性。