C ++类和构造函数

时间:2012-11-12 10:12:18

标签: c++ class constructor

  

可能重复:
  What is an undefined reference/unresolved external symbol error and how do I fix it?

有人想节省一些关于类和构造函数如何在c ++中工作的时间吗?这就是我得到的 - 它不起作用。我想让类具有一个构造函数,该构造函数接受文件名并从文件系统中读取具有该名称的文件。

这是标题和实现

#ifndef __narcissism__Histogram__
#define __narcissism__Histogram__

#include <iostream>
#include <sstream>  // for ostringstream
#include <iomanip>  // for setw, setfill
#include <ios>      // for hex stream manipulator
using namespace std;
#include "random.h" // for randomInteger
#include "strlib.h" // for integerToString
#include "error.h"  // for error



class Histogram {
public:

/** Constructor:
  * 
  *  */
Histogram(string filename)
{
    readfile(filename);

}


private:

int readfile(string filename);

};




#endif /* defined(__narcissism__Histogram__) */

*。CPP

 #include "Histogram.h"



 int readfile(string filename)
 {
 return 0;
 }

错误消息:

Undefined symbols for architecture i386:
"Histogram::readfile(std::string)", referenced from:
  Histogram::Histogram(std::string) in narcissism.o
ld: symbol(s) not found for architecture i386

2 个答案:

答案 0 :(得分:2)

您必须在成员函数的定义中添加Histogram::

 int Histogram::readfile(string filename)
 {
 return 0;
 }

否则它将定义一个具有相同名称的新全局函数,使成员函数未定义。

答案 1 :(得分:2)

您的错误是readfile是Histogram的成员,所以在.cpp文件中它应该是:

int Histogram::readfile( string filename )
{
     // implement
}

你写的函数实际上在这一点上实际上是一个有效的函数。 (如果它试图访问任何Histogram的成员,它会在编译时失败,这可能是readfile的正确实现:目的肯定是将这些成员设置为从文件读取的数据。)

您收到了链接错误,因为没有为名为readfile的函数定义实现,该函数是直方图类的成员。

相关问题