代码是从教科书上抄的。
文件1:test.h
class Point{
public:
Point(int x=0,int y=0):x(x),y(y){}
Point(const Point &p);
~Point(){count--;}
int getX() const {return x;}
int getY() const {return y;}
static void showCount();
private:
int x,y;
static int count;
};
文件2:test.cpp
#include "test.h"
#include <iostream>
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="<<count<<endl;
}
文件3,主函数
#include "test.h"
#include <iostream>
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;
}
我检查了很多次,后面试着把它们全放在一个文件了是可以正常运行的,但分开就不知道问题是出在哪里了,百度也没找到答案。
新手自学,大概犯的是很低级的错误,希望有人指点一下。
链接错误。看看有没有把test.cpp也编译链接进去了。
###g++ test1.cpp test.cpp
是可以编译通过的,检查一下你的IDE配置