gpt4 book ai didi

c++ - 错误 : conversion from ‘const char (*)[11]’ to non-scalar type ‘L::Entry’ requested g++ 4. 4.5

转载 作者:太空宇宙 更新时间:2023-11-04 16:31:31 25 4
gpt4 key购买 nike

好吧,所以我正在制作一个字典类,它采用另一个自制类的数组:条目...我正在尝试制作一个条目数组...我最终设法消除了大部分错误...除了指出错误的一个在 cstdio 中:

error: conversion from ‘const char (*)[11]’ to non-scalar type ‘L::Entry’ requested

我想不出有什么问题,但我已经指出数组初始化是错误启动的原因...这是测试我的 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

提前致谢...

最佳答案

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) { }

并删除另一个采用非常量 char* 的构造函数。不需要!

关于c++ - 错误 : conversion from ‘const char (*)[11]’ to non-scalar type ‘L::Entry’ requested g++ 4. 4.5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6375270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com