这个例子的编译环境是VC 6.0,所以每个cpp文件都要带头文件为:
#include "stdafx.h"
这个例子共用到3个文件,一个头文件,一个源文件,一个main文件。
如下所示:
test.h:
#ifndef _FRACTION_H_
#define _FRACTION_H_
#include <string>
using namespace std;
class Test {
public:
void set(int xx, int yy);
double toDouble() const;
double otherDouble();
void toString() const;
private:
int x;
int y;
};
#endif
test.cpp:
#include "StdAfx.h"
#include "test.h"
#include <iostream>
using namespace std;
void Test::set(int xx,int yy){
x=xx;
y=yy;
}
double Test::toDouble() const{
return x*y;
}
double Test::otherDouble(){
return 10*x*y;
}
void Test::toString() const{
cout<<x<<endl;
cout<<y<<endl;
}
main文件:
// HelloProject.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include "test.h"
using namespace std;
const int DASHES = 30;
int main(int argc, char* argv[])
{
//printf("Hello World!\n");
//cout<<"helloworld"<<endl;
//DASHES++;
cout<<DASHES<<endl;
//
Test t;
t.set(1,2);
t.toString();
return 0;
}
本例子中只是简单介绍了C++类的定义以及实现还有在main文件中的使用。关于更进一步的介绍,待续之。