gpt4 book ai didi

c++ - 识别导致 "non-POD type ' 类段的错误“”

转载 作者:搜寻专家 更新时间:2023-10-31 01:14:16 24 4
gpt4 key购买 nike

我的代码中发生错误的部分:

int disk::access (const char fname[]){

int char_count=77;
int actual_count=0; //just to pass the tests.
char c;

cout << "the file name is " << fname << ", and the mode is " << mode << endl;
if(strcmp(mode, "w")==0){
for (int i = 0; i < size; i++) {
//cout << "sgm to be written is " << sgm[i];
fp=fopen(fname, "w");
fprintf(fp, "%s\n",sgm[i]);
}
fclose(fp);
}
if(strcmp(mode,"a")==0){
fp=fopen(fname, "a");
fprintf(fp, "%s\n", sgm);
fclose(fp);
}

fp=fopen(fname, "r");

do{
c=fgetc(fp);
if(c!=' ' && c!='\n')
actual_count++;
}while(c!=EOF);
fclose(fp);


return actual_count;
}

我的错误:

disk.cpp: In member function 'int disk::access(const char*)':

disk.cpp:67: warning: cannot pass objects of non-POD type 'class segment' through '...'; call will abort at runtime

编辑 第 67 行是:fprintf(fp, "%s\n",sgm[i]);

编辑 SGM:

cpp代码:

disk::disk(int num_of_segments, const char* temp_mode){

size=num_of_segments;
sgm = new segment[size]; //initializes num_of_segments in a disk

count=0;
if(strcmp(mode, "w")!=0||strcmp(mode, "a")!=0){
strcpy(mode, "w");
}

}

disk::disk(){

sgm = new segment[20]; //initialize 20 segments in a disk
size=20; //keeps track of how many are initialized
count=0; //keeps track of how many are added
strcpy(mode, "w"); //initialize disk access mode to w


}

头部代码:

class disk {
private:
int size, count; //to keep a track of number of segments
char mode [2]; //a for append and w for write
segment* sgm;
FILE *fp;

public:
disk(int num_of_segments, const char *temp_mode);
disk();
~disk();
const char* get_mode( ) const;
segment get_segment(int pos) const;
int get_segment_count( ) const;
const segment* get_all_segments( ) const;
int access(const char fname[ ]);
disk& operator+=(const segment &rhs);
disk& operator=(const disk &dk);
};

我以前从未遇到过这样的警告。我做了一些搜索,从我收集到的 POD 是“没有构造函数、析构函数和虚拟成员函数的结构的普通旧数据”。 -格雷格·休吉尔

所以如果我理解正确的话,我的错误是我确实有构造函数或析构函数和/或虚拟成员函数,因为它是非 POD?

我想我只是把自己弄糊涂了,我不确定如何解决这个错误,甚至不知道如何查明问题发生的位置。

欢迎并非常感谢所有建议,

谢谢。

最佳答案

我会大胆猜测并说“段”是一个结构或类,而您正试图将其打印为“%s”字符串。

您需要实现一个将段转换为字符串的函数。或打印段的各个 native 字段。

例如如果您这样定义段

struct segment { char name[10]; int index; }

应该处理为

print("%s:%d\n", seg.name, seg.index);

或作为

inline std::ostream& operator << (std::ostream& os, const struct segment& seg)
{
return os<<seg.name<<":"<<seg.index;
}

并且您的方法调用变为:

std::ostringstream os;
os<<seg;
std::string segStr = os.str();
printf("%s\n", segStr.c_str());

您还可以手动编写一个 toString() 类型的函数来获取段的字符串表示形式。

关于c++ - 识别导致 "non-POD type ' 类段的错误“”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11636412/

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