类的定义(.h):
class Point
{
public:
Point(int x=0,int y=0):x(x),y(y){}
Point(const Point &p);
~Point(){count--;}
int getX(){return x;}
int getY(){return y;}
static void showCount();
private:
int x,y;
static int count;
};
类的实现(.cpp):
#include
#include"Point.h"
using namespace std;
int Point::count=0;
Point::Point(const Point &p):x(p.x),y(p.y)
{
count++;
}
void Point::showCount()
{
cout<<"Object count="< }
主函数(.cpp):
#include
#include"Point.h"
using namespace std;
int main()
{
Point a(4,5);
cout<<"Point A:"<<a.getX()<<","<<a.getY();
Point::showCount();
Point b(a);
cout<<"Point B:"<<b.getX()<<","<<b.getY();
Point::showCount();
return 0;
}
主函数的文件运行不了,这是为什么
你的程序写法有问题,类定义应该放在头文件中,
头文件定义如下
#ifndef POINT_H_
#define POINT_H_
#include<iostream>
class Point
{
public:
Point(int x = 0, int y = 0) :x(x), y(y){}
Point(const Point &p);
~Point(){ count--; }
int getX(){ return x; }
int getY(){ return y; }
static void showCount();
private:
int x, y;
static int count;
};
//int Point::count = 0;
int Point::count = 0;
Point::Point(const Point &p) :x(p.x), y(p.y)
{
count++;
}
void Point::showCount()
{
std::cout << "Object count=" << std::endl;
}
#endif
主程序如下:
#include<iostream>
#include"Point.h"
using namespace std;
int main()
{
Point a(4, 5);
cout << "Point A:" << a.getX() << "," << a.getY();
Point::showCount();
Point b(a);
cout << "Point B:" << b.getX() << "," << b.getY();
Point::showCount();
system("pause");
return 0;
}
把错误报告贴出来,好解决点。
Point(1).cpp:(.text+0x79): undefined reference to Point::showCount()'
Point::Point(Point const&)'
Point(1).cpp:(.text+0x89): undefined reference to
Point(1).cpp:(.text+0xe0): undefined reference to Point::showCount()'
Point::count'
Point(1).cpp:(.rdata$.refptr._ZN5Point5countE[.refptr._ZN5Point5countE]+0x0): undefined reference to
[Error] ld returned 1 exit status