识别导致"非POD类型'类段' "

时间:2012-07-24 17:46:10

标签: c++ std segments

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

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:在成员函数'int disk :: access(const char *)'中:

     

disk.cpp:67:警告:无法传递非POD类型的对象类   段'通过'...'; call将在运行时中止

编辑 第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是“普通的旧数据,这是一个没有构造函数,析构函数和虚拟成员函数的结构。” -Greg Hewgill

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

我想我只是在困惑自己,我不知道如何解决这个错误,甚至找不到问题所在。

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

感谢。

2 个答案:

答案 0 :(得分:3)

我会猜测并说“segment”是一个结构或类,你试图将它打印为“%s”字符串。

您需要实现一个将段转换为字符串的函数。或打印细分的个别原生字段。

e.g。如果你定义了像这样的段

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()类型函数来获取段的字符串表示。

答案 1 :(得分:1)

如果sgm包含virtual方法,或者是classstruct,那么您依赖于该行的实施:

fprintf(fp, "%s\n",sgm[i]);

使用%s,您告诉fprintf sgm[i]char*。如果sgm[i]具有虚函数,则很可能是假的(因为vfptr)。如果该类型的成员布局没有将char*作为第一个数据成员,那么这将再次为假。

相关问题