好吧所以我正在制作另一个自制类的数组的字典类:Entry ...我正在尝试创建一个条目数组......我最终设法摆脱了大多数错误......除了一个说明错误的是cstdio:
错误:从'const char(*)[11]'转换为非标量类型'L :: Entry'请求
我无法弄清楚是否有任何错误,但我已经指出数组初始化是错误启动...继承我测试我的Entry类的主文件的代码:
#include "Entry.cpp"
#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;
using namespace L;
int main(){
Entry entry("word", "definition");
cout << "entry's word is: " << entry.getWord() << endl;
cout << "entry's definition is: " << entry.getDefinition() << endl;
cout << "\n\n\n" << endl;
Entry entries[2] = {
&Entry("Word", "Definition"),
&Entry("Otherword", "OtherDefiniin")
};
cout << "entries's word is: " << entries[1].getWord() << endl;
cout << "entries's definition is: " << entries[1].getDefinition() << endl;
return 0;
}
这里是Entry.cpp:
#include "Entry.h"
#include <string.h>
namespace L
{
//constructors and destructors
Entry::Entry(const char *word, const char *def) : word(word), def(def){}
Entry::Entry(Entry &entryObj) : word(entryObj.word), def(entryObj.def){}
Entry::~Entry(){}
//setter methods
void Entry::setWord(char *newWord){Entry::word = newWord;}
void Entry::setDefinition(char *newDef){Entry::word = newDef;}
//getter methods
std::string Entry::getWord(){return Entry::word;}
std::string Entry::getDefinition(){return Entry::def;}
}
最后是Entry.h:
#include <cstdlib>
#include <cstring>
#include <string>
#include <string.h>
#ifndef ENTRY_H
#define ENTRY_H
namespace L
{
class Entry
{
public:
//constructors and destructors
Entry(const char *word = "", const char *def = "");
Entry(Entry &entryObj);
virtual ~Entry();
//setter methods
void setWord(char *newWord);
void setDefinition(char *newDef);
//getter methods
std::string getWord();
std::string getDefinition();
private:
std::string word;
std::string def;
};
}
#endif
提前感谢...
答案 0 :(得分:5)
Entry entries[2] = {
&("Word", "Definition"),
&("Otherword", "OtherDefiniin")
};
什么是&(....)
?
我认为你的意思,
Entry entries[2] = {
Entry("Word", "Definition"),
Entry ("Otherword", "OtherDefiniin")
};
此外,
Entry::Entry(const char *word, const char *def){
strcpy(Entry::word, word);
strcpy(Entry::def, def);
}
首先,你为什么要写Entry::word
?此外,您还没有为word
分配内存。
我建议您使用std::string
代替char*
:
//put them in the class definition
std::string word;
std::string def;
//constructor definition outside the class
Entry::Entry(const char *word, const char *def) : word(word), def(def) { }
并删除其他带有非const char*
的构造函数。它不需要!
答案 1 :(得分:0)
我弄清楚了......在弄乱Nawaz给我的代码之后。我终于,由于某种原因启用了所有警告并找到了“临时地址”我查了一下然后决定尝试使数组等于预先初始化的对象...即
Entry *entry("Word","Definition");
Entry *entry2("Word2","Definition2");
Entry *entries[2];
entries[0] = &entry;
entries[1] = &entry2;
它最终没有运行时错误或编译器错误