分配字符错误:
structplusclass.cpp: In constructor ‘Soldado::Soldado(char, unsigned int, char, char, char)’:
structplusclass.cpp:25:27: error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive]
strcpy(mTodos.modelo, mol);
^
In file included from /usr/include/c++/5/cstring:42:0,
from structplusclass.cpp:2:
/usr/include/string.h:125:14: note: initializing argument 2 of ‘char* strcpy(char*, const char*)’
extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
^
structplusclass.cpp:27:29: error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive]
strcpy(mTodos.material, mat);
^
In file included from /usr/include/c++/5/cstring:42:0,
from structplusclass.cpp:2:
/usr/include/string.h:125:14: note: initializing argument 2 of ‘char* strcpy(char*, const char*)’
extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
^
structplusclass.cpp:28:18: error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive]
strcpy(mNome, ns);
代码:
#include <iostream>
#include <cstring>
#define SIZE 20
using namespace std;
struct faca {
char modelo[SIZE];
unsigned int peso;
char material[15];
};
class Soldado {
public:
Soldado (char ns, unsigned int p, char mat, char arm, char mol);
~Soldado ();
void Imprime();
protected:
faca mTodos;
char mNome[SIZE];
char mArmapri[SIZE];
};
Soldado::Soldado (char ns, unsigned int p, char mat, char arm, char mol) {
strcpy(mTodos.modelo, mol);
mTodos.peso = p;
strcpy(mTodos.material, mat);
strcpy(mNome, ns);
strcpy(mArmapri, arm);
}
void Soldado::Imprime () {
cout << "Soldado : " << mNome << ", " << "firearm : "
<< mArmapri << endl;
cout << endl << " Faca : " << mTodos.modelo << ", "
<< "lenght : " << mTodos.peso << ", " << "Material : "
<< mTodos.material << endl;
}
Soldado::~Soldado () {
mTodos.peso = 0;
}
int main() {
char names1[SIZE], fire[SIZE];
char names2[SIZE], mat[15];
unsigned int eight;
cout << "nome Soldado, nome arma de fogo " << endl;
cin >> names1 >> fire;
cout << "modelo faca e material " << endl;
cin >> mat >> names2;
cout << "peso" << endl;
cin >> eight;
Soldado brazil(names1, eight, mat, fire, names2);
brazil.Imprime();
return 0;
}
答案 0 :(得分:1)
Soldado :: Soldado()使用了错误的参数。
char names1[SIZE], fire[SIZE];
cout << "nome Soldado, nome arma de fogo " << endl;
cin >> names1 >> fire;
Soldado brazil(names1, ..., ..., fire, ...);
此处names1
和fire
都声明为char[SIZE]
类型。这意味着有SIZE
个类型char
的项目在内存中排成一行(具体来说,在堆栈中,但这对于了解这一点并不重要)。但是然后你将这些传递给你的构造函数,你的构造函数期望这样:
Soldado::Soldado (char ns, ..., ..., char arm, ...) { ... }
此处,ns
和arm
被声明为char
类型,这是char
类型的单个项目,而不是像上面那样的列表。
解决此问题的最佳方法是将ns
和arm
(以及期待单词的其他参数)从char
更改为char[SIZE]
。这将纠正您的编译器错误,并使您的代码正常工作。
然而,还有一点点。你的构造函数有几行代码:
strcpy(mTodos.modelo, mol);
只要您的用户永远不会输入超过19个字母的名称(留下一个char
来标记结尾),这些将完美无缺。但是如果他们输入更长的名字,你的代码就会愉快地写出你为它保留的内存的末尾。你应该用`strncpy()函数来保护你的记忆:
strncpy(mTodos.modelo, mol, SIZE);
mTodos.modelo[SIZE - 1] = '\0';
不幸的是,你需要第二行来确保字符串以null
字符结尾,因为strncpy()
不会一直为你做。